3種python呼叫其他指令碼的方法
1.用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如下:
#!/usr/local/bin/python3.7 print('hello world')
執行結果:
[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()
#!/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) print('Good Bye')
shell指令碼如下:
#!/bin/sh echo "hello world"
執行結果:
[python@master2 while]$ python a.py
hello world
this count is: 1this 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()
#!/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) 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()方法。
總結
以上所述是小編給大家介紹的3種python呼叫其他指令碼的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!