文章目录
一、subprocess 子进程管理模块
subprocess 模块是python官方在3.5版本之后推崇的,用于替代之前的老旧模块与功能。
模块主要介绍以官方文档为主:https://docs.python.org/zh-cn/3/library/subprocess.html#
os.system
os.spawn*
subprocess的主要方法
import subprocess
print(dir(subprocess))
>>>['CalledProcessError', 'CompletedProcess', 'DEVNULL', 'PIPE', 'Popen', 'STDOUT', 'SubprocessError', 'TimeoutExpired', '_PIPE_BUF', '_PLATFORM_DEFAULT_CLOSE_FDS', '_PopenSelector', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_active', '_args_from_interpreter_flags', '_cleanup', '_mswindows', '_optim_args_from_interpreter_flags', '_posixsubprocess', '_time', 'builtins', 'call', 'check_call', 'check_output', 'errno', 'getoutput', 'getstatusoutput', 'io', 'list2cmdline', 'os', 'run', 'select', 'selectors', 'signal', 'sys', 'threading', 'time', 'warnings']
subprocess.run
a = subprocess.run("ls", shell=True) # 需要shell=True,不然错误状态下直接报错
print("func run")
print(type(a))
print(a)
>>>func run
>>><class 'subprocess.CompletedProcess'>
>>>CompletedProcess(args='ls', returncode=0)
run 方法的返回是一个CompletedProcess对象
subprocess.call/check_call
# a = subprocess.call("ls", shell=True) # 需要shell=True,不然错误状态下直接报错
# print("func call")
# print(type(a))
# print(a)
a = subprocess.check_call("ls", stdout=False)
print("func check_call")
print(type(a))
print(a)
>>>func call
>>><class 'int'>
>>>0
>>>func check_call
>>><class 'int'>
>>>0
call方法和check_call方法均返回脚本回执码
subprocess.check_output
a = subprocess.check_output("ls")
print("func check_output")
print(type(a))
print(a)
>>>func check_output
>>><class 'bytes'>
>>>b'1 pd.py\n__init__.py\n__pycache__\nadmin.py\napps.py\nconstant.py\nmigrations\nmodels.py\nscript_event_trect.py\nserializer.py\nsubprocess_demo.py\ntasks.py\ntest1.py\ntests.py\nurls.py\nviews.py\n'
check_output方法返回butes类型输出
subprocess.getstatusoutput
a = subprocess.getstatusoutput("ll")
print("func getstatusoutput")
print(type(a))
print(a)
>>>func getstatusoutput
>>><class 'tuple'>
>>>(127, '/bin/sh: ll: command not found')
getstatusoutput方法返回回执码和输出,这个挺好用的
在执行“nohup”脚本时的注意事项:
code, out_put = subprocess.getstatusoutput("nohup python3 %s %s > %s" % (script_path, script.args, log_path))
- 不能使用&,会导致无法捕获到异常状态码
- 不能使用2>1 会导致无终端输出,仅有日志输出,从而无法捕获输出