Python - 子进程 - 如何在 Windows 中调用管道命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1046474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Subprocess - How to call a Piped command in Windows?
提问by Greg
How do I run this command with subprocess?
如何使用子进程运行此命令?
I tried:
我试过:
proc = subprocess.Popen(
'''ECHO bosco|"C:\Program Files\GNU\GnuPG\gpg.exe" --batch --passphrase-fd 0 --output "c:\docume~1\usi\locals~1\temp\tmptlbxka.txt" --decrypt "test.txt.gpg"''',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
stdout_value, stderr_value = proc.communicate()
but got:
但得到:
Traceback (most recent call last):
...
File "C:\Python24\lib\subprocess.py", line 542, in __init__
errread, errwrite)
File "C:\Python24\lib\subprocess.py", line 706, in _execute_child
startupinfo)
WindowsError: [Errno 2] The system cannot find the file specified
Things I've noticed:
我注意到的事情:
- Running the command on the windows console works fine.
- If I remove the ECHO bosco| part, it runs fine the the popen call above. So I think this problem is related to echo or |.
- 在 Windows 控制台上运行命令工作正常。
- 如果我移除 ECHO bosco| 部分,它在上面的 popen 调用中运行良好。所以我认为这个问题与echo或|有关。
回答by phihag
First and foremost, you don't actually need a pipe; you are just sending input. You can use subprocess.communicatefor that.
首先,您实际上并不需要管道;你只是在发送输入。您可以为此使用subprocess.communicate。
Secondly, don't specify the command as a string; that's messy as soon as filenames with spaces are involved.
其次,不要将命令指定为字符串;一旦涉及带空格的文件名,这就会很混乱。
Thirdly, if you really wanted to execute a piped command, just call the shell. On Windows, I believe it's cmd /c program name arguments | further stuff
.
第三,如果您真的想执行管道命令,只需调用 shell。在 Windows 上,我相信它是cmd /c program name arguments | further stuff
.
Finally, single back slashes can be dangerous: "\p"
is '\\p'
, but '\n'
is a new line. Use os.path.join()or os.sepor, if specified outside python, just a forward slash.
最后,单反斜杠可能很危险:"\p"
is '\\p'
,但是'\n'
是一个新行。使用os.path.join()或os.sep或者,如果在 python 之外指定,只需一个正斜杠。
proc = subprocess.Popen(
['C:/Program Files/GNU/GnuPG/gpg.exe',
'--batch', '--passphrase-fd', '0',
'--output ', 'c:/docume~1/usi/locals~1/temp/tmptlbxka.txt',
'--decrypt', 'test.txt.gpg',],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
stdout_value, stderr_value = proc.communicate('bosco')
回答by Jamie Czuy
You were right, the ECHO is the problem. Without the shell=True option the ECHO command cannot be found.
你是对的,ECHO 是问题所在。如果没有 shell=True 选项,则无法找到 ECHO 命令。
This fails with the error you saw:
这失败了你看到的错误:
subprocess.call(["ECHO", "Ni"])
This passes: prints Ni and a 0
这通过:打印 Ni 和 0
subprocess.call(["ECHO", "Ni"], shell=True)