在python中使用subprocess调用子进程

本博文整理自博友文章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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值