Multiple shell commands in python (Windows)

浪尽此生 提交于 2020-01-17 01:11:10

问题


I'm working on a windows machine and I want to set a variable in the shell and want to use it with another shell command, like:

set variable = abc
echo %variable%

I know that I could do this using os.system(com1 && com2) but I also know, that this is considered 'bad style' and it should be possible by using the subprocess module, but I don't get how. Here is what I got so far:

proc = Popen('set variable=abc', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
proc.communicate(input=b'echo %variable%)

But neither line seems to work, both commands don't get executed. Also, if I type in nonexisting commands, I don't get an error. How is the proper way to do it?


回答1:


Popen can only execute one command or shell script. You can simply provide the whole shell script as single argument using ; to separate the different commands:

proc = Popen('set variable=abc;echo %variable%', shell=True)

Or you can actually just use a multiline string:

>>> from subprocess import call
>>> call('''echo 1
... echo 2
... ''', shell=True)
1
2
0

The final 0 is the return-code of the process

The communicate method is used to write to the stdin of the process. In your case the process immediately ends after running set variable and so the call to communicate doesn't really do anything.

You could spawn a shell and then use communicate to write the commands:

>>> proc = Popen(['sh'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
>>> proc.communicate('echo 1; echo 2\n')
('1\n2\n', '')

Note that communicate also closes the streams when it is done, so you cannot call it mulitple times. If you want an interactive session you hvae to write directly to proc.stdin and read from proc.stdout.


By the way: you can specify an env parameter to Popen so depending on the circumstances you may want to do this instead:

proc = Popen(['echo', '%variable%'], env={'variable': 'abc'})

Obviously this is going to use the echo executable and not shell built-in but it avoids using shell=True.



来源:https://stackoverflow.com/questions/51969420/multiple-shell-commands-in-python-windows

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