1

In my program I want to let the user either run a shell command or execute a binary file. No matter how much I read about subprocess.Popen I can't figure out a way to replicate the os.system() functionality.

I simply want to echo $USER but nothing seems to work.

Turning shell=True..

>>> subprocess.Popen(['echo', '$USER'], shell=True,\
                     stdout=subprocess.PIPE,\
                     stderr=subprocess.PIPE).communicate()
>>> ('\n', '')

Passing current environment vars..

>>> subprocess.Popen(['echo', '$USER'], shell=True,\
                     env=os.environ\
                     stdout=subprocess.PIPE,\
                     stderr=subprocess.PIPE).communicate()
>>> ('\n', '')

So what's the proper way to run a shell command?

------- Edit: requirements ---------

Some people posted answers but maybe I should be more specific. I want to keep both stdout, stderr and return value stored somewhere. All answers seem to give either the one or the other.

Pithikos
  • 18,827
  • 15
  • 113
  • 136

3 Answers3

1

use call method

subprocess.call('echo $USER',shell=True)

Altarnetivly:

var = subprocess.check_output('echo $USER',shell=True) # .rstrip('\n')
print var

Also with subprocess.Popen()

process = subprocess.Popen("echo $USER",shell=True,stdout=subprocess.PIPE)
print process.communicate()[0],
PYPL
  • 1,819
  • 1
  • 22
  • 45
1

Thanks to massiou direction I figured out the answer. The culprit is that when using shell=True you should pass the whole command as a single string!

>>> subprocess.Popen(['echo $USER'], shell=True, \
                     stdout=subprocess.PIPE,\
                     stderr=subprocess.PIPE).communicate()
>>> ('manos\n', '')

The reason is that the first argument in the list will be the one executed as a shell script. The rest arguments are for the shell program itself.

Pithikos
  • 18,827
  • 15
  • 113
  • 136
0

You can just do something like:

subprocess.call('echo $USER', shell=True)

Also, take a look at Replacing Older Functions with the subprocess Module

avamsi
  • 389
  • 3
  • 16