如何執行外部命令,如ls -l
html
使用subprocess
庫python
在Python 3.5以前,使用subprocess.call()
函數shell
>>> import subprocess >>> subprocess.call(['ls', '-l']) total 4 drwxrwxr-x 4 root root 4096 Apr 18 02:46 test-rs 0
在Python3.5及以後,使用subprocess.run()
函數微信
>>> import subprocess >>> subprocess.run(['ls', '-l']) total 4 drwxrwxr-x 4 root root 4096 Apr 18 02:46 test-rs CompletedProcess(args=['ls', '-l'], returncode=0)
命令的執行默認不須要shell環境,因此當你使用ls -l
做爲參數時,須要將shell置位True,不然會報錯誤ide
>>> import subprocess >>> subprocess.run('ls -l', shell=True) total 4 drwxrwxr-x 4 root root 4096 Apr 18 02:46 test-rs CompletedProcess(args=['ls', '-l'], returncode=0)
一般來講對於執行系統命令,咱們會想到os.system
,但在官方文檔中已經建議了使用更高級的subprocess
庫函數
Thesubprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in thesubprocess
documentation for some helpful recipes.
subprocess
提供了更高級的用法,好比run
能夠指定stdin
、stdout
、stderr
,而且能夠指定編碼、超時時間等等選項,還能夠獲取到命令的返回結果this
更多關於subprocess
庫見:https://docs.python.org/3/lib...編碼
Stack Overflowspa
歡迎關注個人微信公衆號:python每日一練code