Running three commands in the same process with Python

≯℡__Kan透↙ 提交于 2019-11-30 05:31:37

Interesting question.

One approach that works is to run a command shell and then pipe commands to it via stdin (example uses Python 3, for Python 2 you can skip the decode() call). Note that the command shell invocation is set up to suppress everything except explicit output written to stdout.

>>> import subprocess
>>> cmdline = ["cmd", "/q", "/k", "echo off"]
>>> cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> batch = b"""\
... set TEST_VAR=Hello World
... set TEST_VAR
... echo %TEST_VAR%
... exit
... """
>>> cmd.stdin.write(batch)
59
>>> cmd.stdin.flush() # Must include this to ensure data is passed to child process
>>> result = cmd.stdout.read()
>>> print(result.decode())
TEST_VAR=Hello World
Hello World

Compare that to the result of separate invocations of subprocess.call:

>>> subprocess.call(["set", "TEST_VAR=Hello World"], shell=True)
0
>>> subprocess.call(["set", "TEST_VAR"], shell=True)
Environment variable TEST_VAR not defined
1
>>> subprocess.call(["echo", "%TEST_VAR%"], shell=True)
%TEST_VAR%
0

The latter two invocations can't see the environment set up by the first one, as all 3 are distinct child processes.

Andreas Jung
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!