4

i get error while plainly using STDOUT

>>> import subprocess
>>>print STDOUT

Traceback (most recent call last): File "", line 1, in NameError: name 'STDOUT' is not defined

it also works with

from subprocess import STDOUT

But what if there are many such constants in the module, is there a way to import any such constants defined in a module without mentioning them explicitly.

ravi.zombie
  • 1,482
  • 1
  • 20
  • 23

1 Answers1

8

You need to tell Python where to find "STDOUT", i.e. in the 'subprocess' module. That's why when you specify "subprocess.STDOUT" it works. If you want to be able to refer to STDOUT without always having to name the module, import it like this:

from subprocess import STDOUT

or, if you are using all of the functions and classes from subprocess, you can import them all like this

from subprocess import *

but it is recommended you avoid this whenever possible for a lot of good reasons (see What exactly does "import *" import?). Otherwise, you should probably just import all of the methods and classes you will use as a tuple in the import statement:

from subprocess import STDOUT, popen, call
Community
  • 1
  • 1
Lgiro
  • 762
  • 5
  • 13
  • Agreed that it works, but what if you have many such constants? for ex, in other submodules to be used? There should be a way to use the constants defined in a submodule without using "from module import CONST" – ravi.zombie Oct 30 '15 at 06:10
  • with version 3.1 and above this will not work anymore. still get error `stdout not defined` – Harry McKenzie Aug 14 '22 at 01:48
  • I cannot reproduce the error you mentioned. Just successfully ran the import (changing popen to Popen) with Python 3.7. Maybe you forgot to capitalize STDOUT? – Lgiro Oct 12 '22 at 03:53