0

I am trying to get output of subprocess.Popen in variable. It is working fine for pwd command, but not working for pwdx $(pgrep -U $USER -f SimpleHTTPServer) command.

This works:

(Pdb++) p = subprocess.Popen("pwd", stdout=subprocess.PIPE)
(Pdb++) result = p.communicate()[0]
(Pdb++) result
'xyz'

This is not working:

(Pdb++) subprocess.Popen("pwdx $(pgrep -U $USER -f SimpleHTTPServer)", stdout=subprocess.PIPE)
*** OSError: [Errno 2] No such file or directory

Can someone please let me know how can I save the output of it to a variable?

2 Answers 2

2

If you want to pass a command with arguments to Popen(), you have to pass it as a list, like so:

subprocess.Popen(['/bin/ls', '-lat'])

If you just pass a single string as in your example, it assumes the entire thing is the command name, and obviously there is no command literally named pwdx $(pgrep -U $USER -f SimpleHTTPServer).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I broke the command into multiple ones and could resolve the issue.
0

As the docs and previous answers already state the command you want to execute via subprocess.Popen() needs to be passed as a list.

From the docs:

Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces) are single list elements.

Another useful tip you can get from the docs is to use shlex.split() to help you to properly split your command into a list.

Beware though that the use of special shell parameters (e.g. $USER) might not work well with subprocess.Popen() unless you would set the shell=True option, which you shouldn't do without reading the doc's Security Considerations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.