Calling Bash Command From Python

Peter Otten __peter__ at web.de
Mon Oct 31 04:12:57 EDT 2016


Wildman via Python-list wrote:

> Python 2.7.9 on Linux
> 
> Here is a bash command that I want to run from a python
> program:  sudo grep "^user\:" /etc/shadow
> 
> If I enter the command directly into a terminal it works
> perfectly.  If I run it from a python program it returns an
> empty string.  Below is the code I am using.  Suggestions
> appreciated.
> 
> cmdlist = ["sudo", "grep", '"^$USER\:"', "/etc/shadow"]
> p = subprocess.Popen(cmdlist,
>                      stdout=subprocess.PIPE,
>                      stderr=subprocess.PIPE)
> shadow, err = p.communicate()
> print shadow

What happens if you hardcode $USER? Compare:

>>> subprocess.Popen(["sudo", "echo", "$USER"], 
stdout=subprocess.PIPE).communicate()
('$USER\n', None)

That should explain the empty result. Possible fix:

>>> subprocess.Popen(["sudo", "echo", os.environ["USER"]], 
stdout=subprocess.PIPE).communicate()
('user\n', None)

While a shell should work, too, 

>>> subprocess.Popen("sudo echo $USER", stdout=subprocess.PIPE, 
shell=True).communicate()
('petto\n', None)

I'd prefer the os.environ lookup.





More information about the Python-list mailing list