Popen and python

混江龙づ霸主 提交于 2020-01-13 09:21:13

问题


Working on some code and I'm given the error when running it from the command prompt...

NameError: name 'Popen' is not defined

but I've imported both import os and import sys.

Here's part of the 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 elementary? I wouldn't doubt it. Thanks!


回答1:


you should do:

import subprocess
subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
# etc.



回答2:


Popen is defined in the subprocess module

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

Or:

from subprocess import Popen
Popen(...)



回答3:


When you import a module, the module's members don't 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 from module import names syntax to import things into the global namespace:

from os import popen    # Or, from os import * to import everything
process = popen(command, mode, bufsize)



回答4:


This looks like Popen from the subprocess module (python >= 2.4)

from subprocess import Popen



回答5:


If your import looks like this:

import os

Then you need to reference the things included in os like this:

os.popen()

If you dont want to do that, you can change your import to look like this:

from os import *

Which is not recommended because it can lead to namespace ambiguities (things in your code conflicting with things imported elsewhere.) You could also just do:

from os import popen

Which is more explicit and easier to read than from os import *




回答6:


You should be using os.popen() if you simply import os.



来源:https://stackoverflow.com/questions/1007855/popen-and-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!