subprocess是用来fork一个子进程的。这个子进程可以运行一个外部程序。
函数:
- subprocess.call()
- subprocess.check_output()
- subprocess.check_call()
这三个函数都调用Popen函数:因此Popen类的初始化函数的入参,都可以通过被上面三个函数使用
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null
'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory
'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
class Popen(object):
_child_created = False # Set here since __del__ checks it
def __init__(self, args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
举例:app_module_list = subprocess.check_output("grep '[INFO] cn.tong' dependency.log | awk '{print $2}' | awk -F':' '{print $2}'", shell=True, cwd=dir)
进入到目录dir后执行shell命令:grep '[INFO] cn.tong' dependency.log | awk '{print $2}' | awk -F':' '{print $2}',标准输出stdout赋值给app_module_list
参考:https://blog.csdn.net/bitcarmanlee/article/details/51622263