3種python調用其餘腳本的方法,你還知道其餘的方法嗎?

1.用python調用python腳本python

#!/usr/local/bin/python3.7
import time
import os 

count = 0
str = ('python b.py')
result1 = os.system(str)
print(result1)
while True:
    count = count + 1
    if count == 8:
      print('this count is:',count) 
      break
    else:
      time.sleep(1)
      print('this count is:',count)   

print('Good Bye')

另一個python腳本b.py以下:shell

#!/usr/local/bin/python3.7
print('hello world')

運行結果:ide

[python@master2 while]$ python a.py 
hello world
this count is: 1
this count is: 2
this count is: 3
this count is: 4
this count is: 5
this count is: 6
this count is: 7
this count is: 8
Good Bye

2.python調用shell方法os.system()學習

'''
遇到問題沒人解答?小編建立了一個Python學習交流QQ羣:579817333 
尋找有志同道合的小夥伴,互幫互助,羣裏還有不錯的視頻學習教程和PDF電子書!
'''
#!/usr/local/bin/python3.7
import time
import os 

count = 0
n = os.system('sh b.sh')
while True:
    count = count + 1
    if count == 8:
      print('this count is:',count) 
      break
    else:
      time.sleep(1)
      print('this count is:',count)   

print('Good Bye')

shell腳本以下:this

#!/bin/sh
echo "hello world"

運行結果:code

[python@master2 while]$ python a.py 
hello world
this count is: 1
this count is: 2
this count is: 3
this count is: 4
this count is: 5
this count is: 6
this count is: 7
this count is: 8
Good Bye

3.python調用shell方法os.popen()視頻

'''
遇到問題沒人解答?小編建立了一個Python學習交流QQ羣:579817333 
尋找有志同道合的小夥伴,互幫互助,羣裏還有不錯的視頻學習教程和PDF電子書!
'''
#!/usr/local/bin/python3.7
import time
import os 

count = 0
n = os.system('sh b.sh')
while True:
    count = count + 1
    if count == 8:
      print('this count is:',count) 
      break
    else:
      time.sleep(1)
      print('this count is:',count)   

print('Good Bye')

運行結果:對象

[python@master2 while]$ python a.py 
<os._wrap_close object at 0x7f7f89377940>
['hello world\n']
this count is: 1
this count is: 2
this count is: 3
this count is: 4
this count is: 5
this count is: 6
this count is: 7
this count is: 8
Good Bye

os.system.popen() 這個方法會打開一個管道,返回結果是一個鏈接管道的文件對象,該文件對象的操做方法同open(),能夠從該文件對象中讀取返回結果。若是執行成功,不會返回狀態碼,若是執行失敗,則會將錯誤信息輸出到stdout,並返回一個空字符串。這裏官方也表示subprocess模塊已經實現了更爲強大的subprocess.Popen()方法。教程

相關文章
相關標籤/搜索