本博文整理自博友文章https://blog.csdn.net/qq_33932782/article/details/79929782。
例子都在ubuntu 18.04上使用python3.6进行测试。
版本上的说明:python2.4之后有subprocess包,python3.5之后官方建议使用subprocess.run()
1. 不捕捉输出(这种可以用在只执行操作,不需要结果的情况,如建立软连接)
函数:
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)
- 如果shell=True,args可以使用字符串,就像写shell一样
>>> subprocess.run("ls -l", shell=True) # doesn't capture output
total 4
drwxr-xr-x 2 chenpan LobeSeg 4096 5月 26 16:14 doc
-rw-r--r-- 1 chenpan LobeSeg 483 6月 25 10:27 init.sh
-rw-r--r-- 1 chenpan LobeSeg 1070 5月 26 16:14 LICENSE.txt
CompletedProcess(args=['ls', '-l'], returncode=0)
- 如果shell=False(默认),args可以是字符串的列表或者元组
>>> subprocess.run(["ls", "-l"]) # doesn't capture output
total 4
drwxr-xr-x 2 chenpan LobeSeg 4096 5月 26 16:14 doc
-rw-r--r-- 1 chenpan LobeSeg 483 6月 25 10:27 init.sh
-rw-r--r-- 1 chenpan LobeSeg 1070 5月 26 16:14 LICENSE.txt
CompletedProcess(args='ls -l', returncode=0)
2. 捕捉输出,以下给出三种实现
- 函数:
subprocess.getoutput(cmd)
例子:
>>> ret = subprocess.getoutput('ls -l')
>>> print(ret)
total 4
drwxr-xr-x 2 chenpan LobeSeg 4096 5月 26 16:14 doc
-rw-r--r-- 1 chenpan LobeSeg 483 6月 25 10:27 init.sh
-rw-r--r-- 1 chenpan LobeSeg 1070 5月 26 16:14 LICENSE.txt
- 函数:
subprocess.getstatusoutput(cmd)
例子:
>>> retcode, output = subprocess.getstatusoutput('ls -l')
>>> print(retcode)
0
>>> print(output)
total 4
drwxr-xr-x 2 chenpan LobeSeg 4096 5月 26 16:14 doc
-rw-r--r-- 1 chenpan LobeSeg 483 6月 25 10:27 init.sh
-rw-r--r-- 1 chenpan LobeSeg 1070 5月 26 16:14 LICENSE.txt
- 函数:
class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False,
startup_info=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())
例子:
>>> import subprocess
>>> p = subprocess.Popen('ls -l', stdout=subprocess.PIPE, shell=True)
>>> print(p.stdout.read())
b'total 4\ndrwxr-xr-x 2 chenpan LobeSeg 4096 5\xe6\x9c\x88 26 16:14 doc\n-rw-r--r-- 1 chenpan LobeSeg 483 6\xe6\x9c\x88 25 10:27 init.sh\n-rw-r--r-- 1 chenpan LobeSeg 1070 5\xe6\x9c\x88 26 16:14 LICENSE.txt\n'