本文目錄一覽:
python shell怎麼使用
Python 中執行 Shell 命令有多種方法,stackoverflow 上有對這些方法進行比較的討論,Calling an external command in Python 指出使用subprocess模塊來實現更優。因此,本文說明如何使用subprocess模塊來實現 Shell 腳本的功能。
subprocess模塊提供多種方法來實現執行 Linux 的命令,例如subprocess.call()方法,subprocess.check_call()方法,等。這些方法都是對Popen類的封裝,故本文著重講述Popen類的使用。
執行 Shell 命令
可以通過向Popen()傳遞需要執行的命令來創建一個Popen對象,這樣,便會創建一個子進程來執行命令。例如:
child = subprocess.Popen([“ping”,”-c”,”5″,”leehao.me”])
1
上面的代碼會創建一個子進程來執行ping -c 5 leehao.me命令,這個命令採用列表的形式傳遞給Popen()方法。如果我們想直接採用ping -c 5 leehao.me字元串形式,可以添加shell=True來實現:
child = subprocess.Popen(“ping -c 5 leehao.me”, shell=True)
1
官方文檔指出由於安全原因故不建議使用shell=True,詳細說明可以參考官方文檔的描述。
等待子進程執行
子進程執行命令後,主進程並不會等待子進程執行。為了讓主進程等待子進程執行結束,需要顯示調用Popen.wait()方法。例如:
child = subprocess.Popen([“ping”,”-c”,”5″,”leehao.me”])
child.wait()
print ‘parent finish’
1
2
3
這樣,主進程會等待子進程執行ping命令完畢後,才會列印出parent finish的輸出。
獲取執行結果
為了獲取Popen()子進程的輸出,可以使用Popen.communicate()方法,例如:
def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout
subprocess_cmd(‘echo leehao.me; echo ‘)
1
2
3
4
5
6
輸出:
leehao.me
process.communicate()方法可以實現主進程與子進程的通信。主進程可以通過它向子進程發送數據,也可以讀取子進程的輸出的數據。上面的例子中,我們在創建Popen對象時指定stdout=subprocess.PIPE,這樣主進程便可以讀取子進程的輸出。
communicate()方法返回一個元組:(stdoutdata, stderrdata),process.communicate()[0]即獲取子進程的標準輸出。
需要指出的是,調用communicate()方法後,主進程也會等待子進程執行完畢。
上面的例子中,子進程向標準輸出列印兩個字元串,主進程接收到了這些輸出,並列印出來。
在Python運行bash命令問題,怎麼解決
最近有個需求就是頁面上執行shell命令,第一想到的就是os.system,
複製代碼代碼如下:
os.system(‘cat /proc/cpuinfo’)
但是發現頁面上列印的命令執行結果 0或者1,當然不滿足需求了。
嘗試第二種方案 os.popen()
複製代碼代碼如下:
output = os.popen(‘cat /proc/cpuinfo’)
print output.read()
通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是無法讀取程序執行的返回值)
嘗試第三種方案 commands.getstatusoutput() 一個方法就可以獲得到返回值和輸出,非常好用。
複製代碼代碼如下:
(status, output) = commands.getstatusoutput(‘cat /proc/cpuinfo’)
print status, output
Python Document 中給的一個例子,
複製代碼代碼如下:
import commands
commands.getstatusoutput(‘ls /bin/ls’)
(0, ‘/bin/ls’)
commands.getstatusoutput(‘cat /bin/junk’)
(256, ‘cat: /bin/junk: No such file or directory’)
commands.getstatusoutput(‘/bin/junk’)
(256, ‘sh: /bin/junk: not found’)
commands.getoutput(‘ls /bin/ls’)
‘/bin/ls’
commands.getstatus(‘/bin/ls’)
‘-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls’
最後頁面上還可以根據返回值來顯示命令執行結果。
python如何使用gitbash執行git命令?
代碼如下:
#!/usr/bin/env python# -*- coding: utf-8 -*-#
@name : find_t.py# @author : cat#
@date : 2017/8/2.import osimport timedef bash_shell(bash_command):
“””
python 中執行 bash 命令 :param bash_command:
:return: bash 命令執行後的控制台輸出
“””
try:
return os.popen(bash_command).read().strip()
except: return Nonedef find_target(target_path=”./../”, key=’.git’):
“””
查找目標目錄所在的目錄 : 如
/aa/bb/.git — return /aa/bb/
:param target_path:
:param key: target
:return:
“””
walk = os.walk(target_path)
for super_dir, dir_names, file_names in walk:
for dir_name in dir_names:
if dir_name == key:
dir_full_path = os.path.join(super_dir, dir_name)
# print(dir_full_path, super_dir, dir_name, sep=” ## “)
yield super_dirif __name__ == ‘__main__’:
print(“start execute bash ………..”)
st = time.time()
cwd = os.getcwd()
# this for repo
f
or repo_path in find_target(os.getcwd(), key=’.repo’):
os.chdir(repo_path)
if repo_path == os.getcwd():
print(‘find repo in –‘, repo_path)
print(bash_shell(‘pwd’))
print(bash_shell(‘repo forall -c git config core.fileMode false –replace-all’))
else:
print(‘error in chdir 2 {}’.format(repo_path))
if os.getcwd() != cwd:
os.chdir(cwd)
if os.getcwd() != cwd:
print(‘change 2 cwd FAIL !!! {}’.format(cwd))
# this for git
for git_path in find_target(os.getcwd(), key=’.git’):
os.chdir(git_path)
if git_path == os.getcwd():
print(‘find git in –‘, git_path)
print(bash_shell(‘pwd’))
print(bash_shell(‘git config –global core.filemode false’))
else:
print(‘error in chdir 2 {}’.format(git_path))
if os.getcwd() != cwd:
os.chdir(cwd)
if os.getcwd() != cwd:
print(‘change 2 cwd FAIL !!! {}’.format(cwd))
et = time.time()
print(‘\n\n
#### execute finished in {:.3f} seconds ####’.format(et – st))
print(‘\n’) # test for bash_command
# print(bash_shell(‘git init’))
# print(bash_shell(‘ls -al’))
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/304724.html