1. 程式人生 > 程式設計 >簡單瞭解python呼叫其他指令碼方法例項

簡單瞭解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: 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()

#!/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()方法。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。