Python - Subprocess - How to invoke the Piped command on Windows?

How to run this command with a 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 received:

 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 

What I noticed:

  • Command execution in windows console works fine.
  • If I remove ECHO bosco | In part, it works the above call perfectly. I think this problem is associated with an echo or |.
+5
python subprocess pipe echo popen
source share
2 answers

First of all, you really don't need a pipe; you just send input. You can use subprocess.communicate for this.

Secondly, do not specify the command as a string; this is randomly as soon as filenames with spaces are involved.

Thirdly, if you really want to execute a command with channels, just call the shell. On Windows, I find it cmd /c program name arguments | further stuff cmd /c program name arguments | further stuff .

Finally, one slash can be dangerous: "\p" is '\\p' , but '\n' is a new line. Use os.path.join () or os.sep or, if specified outside of python, just a slash.

 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') 
+11
source share

You were right, the ECHO problem. Without the shell = True option, the ECHO command cannot be found.

This is not with the error you saw:

 subprocess.call(["ECHO", "Ni"]) 

It passes: prints Ni and 0

 subprocess.call(["ECHO", "Ni"], shell=True) 
+4
source share

All Articles