Calling Bash Command From Python

Wildman best_lay at yahoo.com
Mon Oct 31 10:55:06 EDT 2016


On Mon, 31 Oct 2016 09:12:57 +0100, Peter Otten wrote:

> 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.

I have code using that approach but I am trying to save myself
from having to parse the entire shadow file.  Grep will do it
for me if I can get code right.

-- 
<Wildman> GNU/Linux user #557453
The cow died so I don't need your bull!



More information about the Python-list mailing list