這篇文章給大家分享的是有關Python執行外部命令的方法的內容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。
調用shell命令
#!/usr/bin/python3 import subprocess # 執行外部命令 'date' subprocess.call('date') # 傳遞選項和參數給命令 print("\nToday is ", end="", flush=True) subprocess.call(['date', '-u', '+%A']) # 其他例子 print("\nSearching for 'hello world'", flush=True) subprocess.call(['grep', '-i', 'hello world', 'hello_world.py'])
這里的import語句用于載入subprocess模塊,它是Python標準庫的一部分
subprocess模塊中的call函數是一種執行外部命令的方式
通過傳遞True給flush參數(默認是False),我們確保這個信息在subprocess.call運行之前輸出
想要給命令傳遞參數,需要使用字符串列表
$ ./calling_shell_commands.py Tue Jun 21 18:35:33 IST 2016 Today is Tuesday Searching for 'hello world' print("Hello World")
使用擴展調用shell命令
#!/usr/bin/python3 import subprocess # 不使用擴展調用Shell命令 print("No shell expansion when shell=False", flush=True) subprocess.call(['echo', 'Hello $USER']) # 使用Shell擴展調用Shell命令 print("\nshell expansion when shell=True", flush=True) subprocess.call('echo Hello $USER', shell=True) # 如果引號是命令的一部分則進行反義 print("\nSearching for 'hello world'", flush=True) subprocess.call('grep -i \'hello world\' hello_world.py', shell=True)
默認subprocess.call不會擴展shell 通配符,使用 command替換等等
可以設定shell參數為True進行重寫
注意現在整個命令行都作為一個字符串而不是字符串列表
命令中含有引號如要轉義
僅在你確定命令會正確執行的情況下使用shell=True,否則會存在安全問題
$ ./shell_expansion.py No shell expansion when shell=False Hello $USER shell expansion when shell=True Hello learnbyexample Searching for 'hello world' print("Hello World")
在特定情況下,我們可以使用單/雙引號的組合來避免使用轉義符號
# 像這樣使用另一種引號 subprocess.call('grep -i "hello world" hello_world.py', shell=True) # 或者這樣 subprocess.call("grep -i 'hello world' hello_world.py", shell=True)
Shell命令重定向可以正常使用
# 為了避免call函數字符串太常,我們使用變量先存儲命令 cmd = "grep -h 'test' report.log test_list.txt > grep_test.txt" subprocess.call(cmd, shell=True)
避開使用shell=True
>>> import subprocess, os >>> subprocess.call(['echo', 'Hello', os.environ.get("USER")]) Hello learnbyexample 0
os.environ.get("USER")返回環境變量USER的值
0退出狀態碼,意味著成功執行了命令。
獲取命令輸出和重定向
#!/usr/bin/python3 import subprocess # 輸出也包含任何的錯誤信息 print("Getting output of 'pwd' command", flush=True) curr_working_dir = subprocess.getoutput('pwd') print(curr_working_dir) # 獲取命令執行的狀態和輸出 # 退出狀態碼不是“0”意味著有什么事情出錯了 ls_command = 'ls hello_world.py xyz.py' print("\nCalling command '{}'".format(ls_command), flush=True) (ls_status, ls_output) = subprocess.getstatusoutput(ls_command) print("status: {}\noutput: '{}'".format(ls_status, ls_output)) # 抑制出錯信息 # subprocess.call()返回命令的狀態碼 returns status of command which can be used instead print("\nCalling command with error msg suppressed", flush=True) ls_status = subprocess.call(ls_command, shell=True, stderr=subprocess.DEVNULL) print("status: {}".format(ls_status))
getstatusoutput()的輸出是元組數據類型,更多信息和例子在后續章節
getstatusoutput()和getoutput()老式的函數
使用有更多特性和安全選項的新函數
$ ./shell_command_output_redirections.py Getting output of 'pwd' command /home/learnbyexample/Python/python_programs Calling command 'ls hello_world.py xyz.py' status: 2 output: 'ls: cannot access xyz.py: No such file or directory hello_world.py' Calling command with error msg suppressed hello_world.py status: 2
感謝各位的閱讀!關于Python執行外部命令的方法就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。