0

I am running into following error when trying to run a command using Popen,what is wrong here?

cmd = "export COMMANDER_SERVER=commander.company.com" Pipe = Popen(cmd, stdout=PIPE, stderr=PIPE) (output, error) = Pipe.communicate() 

Error:-

Traceback (most recent call last): File "test_ectool.py", line 26, in <module> main() File "test_ectool.py", line 13, in main Pipe = Popen(cmd, stdout=PIPE, stderr=PIPE) File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory 
2
  • 1
    What are you trying to accomplish by running that command? Even if it worked, the command would have no effect on anything. You'd just be setting an environment variable in the child process which would be lost as soon as the child process exits. Commented May 23, 2014 at 20:32
  • 1
    That's not how you set environment variables from Python. Use os.environ['COMMANDER_SERVER'] = 'commander.company.com'. Commented May 23, 2014 at 20:34

2 Answers 2

2
  1. You need to separate the arguments from the command and give a list to Popen.
  2. As Kenster's comment said, even if your command worked, you would only succeed in modifying an environmental variable inside a sub-shell not the main shell.
  3. You will not be able run run export this way, because it is not a program. It is a bash built-in.

Here is an example of a command that does work, with the correct semantics.

from subprocess import Popen,PIPE cmd = "echo COMMANDER_SERVER=commander.company.com" Pipe = Popen(cmd.split(), stdout=PIPE, stderr=PIPE) (output, error) = Pipe.communicate() print output 
Sign up to request clarification or add additional context in comments.

Comments

0

merlin2011's answer is incorrect regarding the command string for Popen (point #1). From the Python docs:

args should be a sequence of program arguments or else a single string.

As other people have stated, the environment variable will not be saved. For that, you need to use os.environ['VARNAME'] = value. If you want to use other bash builtins, then you must pass shell=True as an argument to Popen.

3 Comments

Also from the docs: Unless otherwise stated, it is recommended to pass args as a sequence.
Furthermore: On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program.
Given his original code and error messages, I assumed he was on a Unix-like system.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.