Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess issue with ampersands

I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.

The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?

To clarify from current responses:

  1. I am using the subprocess module
  2. I am passing the command line + arguments in as a list
  3. The issue is with the path to the command itself, not any of the arguments
  4. I've tried quoting the command. It causes a [Error 123] The filename, directory name, or volume label syntax is incorrect error
  5. I'm using no shell argument (so shell=false)
  6. In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin
  7. It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.
  8. The command that is failing is:

p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)

when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.

like image 789
workmad3 Avatar asked Jan 24 '23 02:01

workmad3


2 Answers

Make sure you are using lists and no shell expansion:

subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)
like image 51
Armin Ronacher Avatar answered Feb 05 '23 03:02

Armin Ronacher


A proper answer will need more information than that. What are you actually doing? How does it fail? Are you using the subprocess module? Are you passing a list of arguments and shell=False (or no shell argument) or are you actually invoking the shell?

like image 23
Thomas Wouters Avatar answered Feb 05 '23 02:02

Thomas Wouters