Popen and python

Work on some code, and I get an error when starting from the command line ...

NameError: name 'Popen' is not defined 

but I imported both import os and import sys .

Here is a piece of code

 exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el', str(el), '-n', str(z)] print 'The python program is running this command:' print cmd process = Popen(cmd, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] 

Am I missing something basic? I would not doubt it. Thank!

+5
python popen
Jun 17 '09 at 15:38
source share
6 answers

you should:

 import subprocess subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) # etc. 
+30
Jun 17 '09 at 15:43
source share

Popen is defined in the subprocess module

 import subprocess ... subprocess.Popen(...) 

Or:

 from subprocess import Popen Popen(...) 
+7
Jun 17 '09 at 15:41
source share

When you import a module, the members of the module do not become part of the global namespace: you still have to prefix them with modulename. . So you have to say

 import os process = os.popen(command, mode, bufsize) 

Alternatively, you can use the syntax from module import names to import objects into the global namespace:

 from os import popen # Or, from os import * to import everything process = popen(command, mode, bufsize) 
+2
Jun 17 '09 at 15:43
source share

If your import looks like this:

 import os 

Then you need to specify things included in os, for example:

 os.popen() 

If you do not want to do this, you can change your import like this:

 from os import * 

This is not recommended because it can lead to namespace ambiguities (things in your code conflict with things imported to another location). You can also just do:

 from os import popen 

What is more understandable and easier to read than from os * import

+1
Jun 17 '09 at 15:42
source share

It looks like Popen from a subprocess module (python> = 2.4)

 from subprocess import Popen 
+1
Jun 17 '09 at 15:43
source share

You should use os.popen () if you just import os.

-one
Jun 17 '09 at 15:40
source share



All Articles