多指令 | 是否阻塞 | 返回类型 | 推荐使用 | ||
---|---|---|---|---|---|
os.system | 支持 | 阻塞 | returncode | ||
subprocess | Popen | 支持 | 根据参数灵活调整 | returncode,stdout,stderr | 推荐 |
call | 支持 | 阻塞 | returncode | ||
check_call | 支持 | 非阻塞 | returncode | 推荐 | |
check_output | 支持 | 非阻塞 | stdout | 推荐 | |
getoutput | 不支持 | 阻塞 | stdout | ||
getstatusoutput | 不支持 | 阻塞 | returncode,stdout |
Help on module subprocess:
NAME
subprocess - Subprocesses with accessible I/O streams
DESCRIPTION
This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.
For a complete description of this module see the Python documentation.
Main API
========
run(...): Runs a command, waits for it to complete, then returns a
CompletedProcess instance.
Popen(...): A class for flexibly executing a command in a new process
Constants
---------
DEVNULL: Special value that indicates that os.devnull should be used
PIPE: Special value that indicates a pipe should be created
STDOUT: Special value that indicates that stderr should go to stdout
Older API
=========
call(...): Runs a command, waits for it to complete, then returns
the return code.
check_call(...): Same as call() but raises CalledProcessError()
if return code is not 0
check_output(...): Same as check_call() but returns the contents of
stdout instead of a return code
getoutput(...): Runs a command in the shell, waits for it to complete,
then returns the output
getstatusoutput(...): Runs a command in the shell, waits for it to complete,
then returns a (status, output) tuple
import os
import sys
import signal
import psutil
import time
import subprocess
if __name__ == '__main__':
oo = ['cd', os.path.abspath('.'),
'&&',
'dir',
'&&'
]
process_cmd = ' '.join(oo)
# outputstatus= subprocess.check_call(process_cmd, shell=True)
# print("return", outputstatus)
pro = subprocess.Popen(process_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True)
returncode = pro.poll()
while returncode is None:
returncode = pro.poll()
back_data = dict(
pid=pro.pid,
output_lines=pro.stdout.readlines(),
error_lines=pro.stderr.readlines())
# os.kill(back_data['pid'], signal.SIGTERM)
print("back \npid {pid} \noutput_lines {output_lines} \nerror_lines {error_lines}".format(
**back_data))
关闭进程及子进程相关相关
import os
import psutil
process = psutil.Process(back_data.get('pid'))
process_children = process.children(recursive=True)
print([{"pid": child.pid, "status": child.status(), "name": child.name()}
for child in process_children])
os.kill(back_data['pid'], signal.SIGTERM)
关闭与名字匹配的进程
import psutil
def kill_process(name):
"""search process ,kill process by name """
kill_pids = []
try:
for process in psutil.process_iter():
if name == process.name():
kill_pids.append(process.pid)
except psutil.NoSuchProcess:
pass
[os.kill(kill_pid, signal.SIGTERM) for kill_pid in kill_pids]
网友评论