简体   繁体   中英

How do I spawn a shell sub-command, with its stdout bound to the parent's stdout in python

I want a python program to spawn a shell sub-command, with the stdout of the shell being written to the stdout of the python parent.

The python script will be run as a CGI, so the shell output should be sent back to the browser.

As python subprocess module docs tell (emphasis mine)

stdin, stdout and stderr specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With the default settings of None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.

So, it should be as easy as

subprocess.call(["your_shell_command", /*command line arguments, if any*/])

Eg

subprocess.call(["ls", "-l"])
subprocess.call(["mkdir", "newdir"])
subprocess.call("your_shell_script.sh")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM