python中的多个shell命令(Windows) [英] Multiple shell commands in python (Windows)
问题描述
我正在Windows机器上工作,我想在shell中设置一个变量,并希望将其与另一个shell命令一起使用,例如:
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%
我知道我可以使用os.system(com1 && com2)
来做到这一点,但我也知道,这被认为是不良样式",应该可以通过使用subprocess模块来实现,但我不知道如何做.
这是到目前为止我得到的:
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?
推荐答案
Popen
只能执行一个命令或shell脚本.您可以简单地使用;
将整个shell脚本作为单个参数提供,以分隔不同的命令:
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
最后的0
是进程的返回码
The final 0
is the return-code of the process
communicate
方法用于写入进程的标准输入.对于您而言,该过程在运行set variable
之后立即结束,因此对communicate
的调用实际上并没有执行任何操作.
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.
您可以生成外壳,然后使用communicate
编写命令:
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', '')
请注意,communicate
完成后还会关闭流,因此您不能多次调用它.如果要进行交互式会话,则可以直接写到proc.stdin
并从proc.stdout
中读取.
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
.
顺便说一句:您可以为Popen
指定一个env
参数,因此视情况而定,您可能希望这样做:
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'})
很明显,这将使用echo
可执行文件,而不是内置的shell,但避免使用shell=True
.
Obviously this is going to use the echo
executable and not shell built-in but it avoids using shell=True
.
这篇关于python中的多个shell命令(Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!