Python 之調用系統命令
- 2020 年 1 月 14 日
- 筆記
在python中執行系統命令的方法有以下幾種:
1.os.system(command)
>>> s = os.system('ls -l') 總用量 56 drwxr-xr-x. 2 root root 4096 4月 16 16:39 down_scripts -rw-r--r--. 1 root root 30 4月 18 11:29 ip.list drwxr-xr-x. 2 root root 4096 4月 23 16:30 mypython drwxr-xr-x. 2 root root 4096 4月 22 09:57 mysource drwxr-xr-x. 3 root root 4096 4月 17 11:51 mywork drwxr-xr-x. 2 root root 36864 3月 19 11:09 pythoncook >>> print s 0 >>> s = os.system('ll -5') sh: ll: command not found >>> print s 32512 #返回值是命令的退出狀態。不能撲捉輸出的內容
2.subprocess.call()
#subprocess.call()執行命令,返回的值是退出資訊 >>> s = subprocess.call('ls -l',shell=True) 總用量 56 drwxr-xr-x. 2 root root 4096 4月 16 16:39 down_scripts -rw-r--r--. 1 root root 30 4月 18 11:29 ip.list drwxr-xr-x. 2 root root 4096 4月 24 14:58 mypython drwxr-xr-x. 2 root root 4096 4月 22 09:57 mysource drwxr-xr-x. 3 root root 4096 4月 17 11:51 mywork drwxr-xr-x. 2 root root 36864 3月 19 11:09 pythoncook >>> print s 0 >>> s = subprocess.call(['ls','-l']) 總用量 56 drwxr-xr-x. 2 root root 4096 4月 16 16:39 down_scripts -rw-r--r--. 1 root root 30 4月 18 11:29 ip.list drwxr-xr-x. 2 root root 4096 4月 24 14:58 mypython drwxr-xr-x. 2 root root 4096 4月 22 09:57 mysource drwxr-xr-x. 3 root root 4096 4月 17 11:51 mywork drwxr-xr-x. 2 root root 36864 3月 19 11:09 pythoncook >>> print s 0 #指令可以是字元串,也可以是列表,但是當是字元串時後面跟參數shell=True 該方式相當於創建個新進程執行系統命令,返回值是進程的退出狀態。
3.subprocess.Popen()
>>> s = subprocess.Popen('ls -l',shell=True,stdout=subprocess.PIPE) >>> print s.stdout.read() 總用量 56 drwxr-xr-x. 2 root root 4096 4月 16 16:39 down_scripts -rw-r--r--. 1 root root 30 4月 18 11:29 ip.list drwxr-xr-x. 2 root root 4096 4月 24 14:58 mypython drwxr-xr-x. 2 root root 4096 4月 22 09:57 mysource drwxr-xr-x. 3 root root 4096 4月 17 11:51 mywork drwxr-xr-x. 2 root root 36864 3月 19 11:09 pythoncook #這方法可獲得輸出。
在python2.7以上的版本,subprocess模組提供了一個可以直接獲得輸出的函數
check_output(*popenargs, **kwargs)
>>> s = subprocess.check_output('ls -l',shell=True) >>> print s 總用量 24 -rw-r--r--. 1 root root 150 5月 12 17:30 ip.txt -rwxr-xr-x. 1 root root 235 5月 12 17:57 jiang.py drwxr-xr-x. 2 root root 4096 5月 8 17:18 mypython drwxr-xr-x. 2 root root 4096 5月 12 13:47 mysource drwxr-xr-x. 4 root root 4096 5月 12 16:02 mywork drwxr-xr-x. 3 root root 4096 5月 10 11:37 web
此時s為字元串