Why a simple echo in a subprocess does not work

I am trying to perform a simple echo operation using a subprocess:

import subprocess import shlex cmd = 'echo $HOME' proc = subprocess.Popen(shlex.split(cmd), shell=True, stdout=subprocess.PIPE) print proc.communicate()[0] 

But he does not print anything. Even if I change the command to echo "hello, world" , it still doesn't print anything. Any help is appreciated.

+8
python linux subprocess
source share
2 answers

In Unix shell=True it is understood that the 2nd and following arguments are for the shell itself, use the line to pass the command to the shell:

 import subprocess cmd = 'echo $HOME' proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) print proc.communicate()[0], 

You can also write it as:

 import subprocess cmd = 'echo $HOME' print subprocess.check_output(cmd, shell=True), 

From the subprocess documents :

On Unix with shell=True shell uses / bin / sh by default. If args is a string, the string indicates the command to execute through the shell. This means that the string must be formatted exactly as it would be when typing on the command line. This includes, for example, quoting or backslashes that skip file names with spaces in them. If args is a sequence, the first element indicates the command line, and any additional elements will be considered as additional arguments for the shell itself. That is, Popen makes the equivalent:

 Popen(['/bin/sh', '-c', args[0], args[1], ...]) 
+10
source share

You mix two different Popen calls. Any of them will work:

 proc=subprocess.Popen(['/bin/echo', 'hello', 'world'], shell=False, stdout=subprocess.PIPE) 

or

 proc=subprocess.Popen('echo hello world', shell=True, stdout=subprocess.PIPE) 

When passing shell = True, the first argument is the string — the shell command line. If you do not use a wrapper, the first argument is a list. Both produce this:

 print proc.communicate() ('hello world\n', None) 
+1
source share

All Articles