示例
- run()
In [2]: subprocess.run(["ls","-l"])
-rw-r--r-- 1 liyuanjie liyuanjie 1350 12月 15 18:33 wireshark.md
Out[2]: CompletedProcess(args=['ls', '-l'], returncode=0)
In [3]: subprocess.run(["ls","-l","/dev/null"],stdout=subprocess.PIPE)
Out[3]: CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0, stdout=b'
crw-rw-rw- 1 root root 1, 3 12\xe6\x9c\x88 15 07:51 /dev/null\n')
- call()
In [4]: subprocess.call(['ls','-l'])
In [5]: subprocess.call('ls -l',shell=True)
In [6]: subprocess.call(['ls','-l'],stdout=subprocess.DEVNULL)
Out[6]: 0
In [7]: subprocess.call(['ls','-l','/services'])
- check_call()
In [9]: subprocess.check_call(['ls','-l'])
In [10]: subprocess.check_call('ls -l',shell=True)
In [11]: subprocess.check_call('ls -l /services',shell=True)
- check_output()
In [12]: ret = subprocess.check_output(['ls','-l'])
In [13]: print(ret) 返回的是字节序列.
In [14]: ret = subprocess.check_output(['ls','-l'],universal_newlines=True)
In [15]: print(ret) 返回的是字符串.
- getoutput()与getstatusoutput()
In [16]: ret = subprocess.getoutput('ls -l')
In [17]: print(ret)
正确情况下:
In [18]: retcode,output = subprocess.getstatusoutput('ls -l')
In [19]: print(retcode)
0
In [20]: print(output)
错误情况下:
In [21]: retcode,output = subprocess.getstatusoutput('ls -l /test')
In [22]: print(retcode)
2
In [23]: print(output)
ls: cannot access '/test': No such file or directory