execute a shell-script from Python subprocess

牧云@^-^@ 提交于 2019-12-03 10:04:22

Using the subprocess library, you can tell the Popen class that you want to manage the standard input of the process like this:

import subprocess
shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE)

Now shellscript.stdin is a file-like object on which you can call write:

shellscript.stdin.write("yes\n")
shellscript.stdin.close()
returncode = shellscript.wait()   # blocks until shellscript is done

You can also get standard out and standard error from a process by setting stdout=subprocess.PIPE and stderr=subprocess.PIPE, but you shouldn't use PIPEs for both standard input and standard output, because deadlock could result. (See the documentation.) If you need to pipe in and pipe out, use the communicate method instead of the file-like objects:

shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = shellscript.communicate("yes\n")   # blocks until shellscript is done
returncode = shellscript.returncode
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!