python -- subprocess

本文介绍了Python中subprocess模块的功能及使用方法,包括替代的旧接口、支持的主要接口、Popen对象的方法属性等,并通过示例展示了如何使用这些方法来与子进程交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

subprocess用于替换一下包的功能

os.system
os.spawn*
os.popen*
popen2.*
commands.*


subprocess支持的接口

1. subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)


2. subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)


3.subprocess.check_output(args,*,stdin=None,stderr=None,sal_newlines=False)

4.class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None,preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, uni-versal_newlines=False, startupinfo=None, creationflags=0)


Popen对象


Popen.poll()

Check if child process has terminated. Set and return returncode attribute.


Popen.communicate(input=None)
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a string to be sent to the child process, or None, if
no data should be sent to the child.


Popen.send_signal(signal)
Sends the signal signal to the child.


Popen.terminate()
Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function
TerminateProcess() is called to stop the child.


Popen.kill()
Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows kill() is an alias for
terminate().


Popen.stdin
If the stdin argument was PIPE, this attribute is a file object that provides input to the child process. Otherwise,
it is None.


Popen.stdout
If the stdout argument was PIPE, this attribute is a file object that provides output from the child process.
Otherwise, it is None.

Popen.wait()
Wait for child process to terminate. Set and return returncode attribute.


Popen.stderr
If the stderr argument was PIPE, this attribute is a file object that provides error output from the child process.
Otherwise, it is None.


Popen.pid
The process ID of the child process.
Note that if you set the shell argument to True, this is the process ID of the spawned shell.


Popen.returncode
The child return code, set by poll() and wait() (and indirectly by communicate()). A None value
indicates that the process hasn’t terminated yet.


例子:

>>> p = subprocess.Popen("aplay -D plughw:1,2 /home/tingzhi.wav", shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> print p.returncode
None
>>> out,err = p.communicate()
>>> print p.returncode
1
>>> print out
aplay: main:722: 音乐打开错误: 没有那个文件或目录
>>> print err
None
>>> print p.wait()
1
>>>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值