Calling Bash Command From Python

Wildman best_lay at yahoo.com
Mon Oct 31 12:16:51 EDT 2016


On Mon, 31 Oct 2016 08:13:54 +0000, Jon Ribbens wrote:

> On 2016-10-31, Wildman <best_lay at yahoo.com> wrote:
>> 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
> 
> Slightly surprised that nobody's pointed out that in your bash
> invocation, the first argument to grep is:
> 
>     ^user\:
> 
> and in the Python code it is:
> 
>     "$USER\:"
> 
> Your cmdlist should read:
> 
>     ["sudo", "grep", r"^user\:", "/etc/shadow"]
> 
> or if you really want it to do the same as the bash:
> 
>     ["sudo", "grep", "^" + os.environ["USER"] + r"\:", "/etc/shadow"]

The above line works perfectly.  I didn't occur to me to use the
'r' modifier.  Thank you.

Still one thing is odd.  No matter what, if I use the environment
variable $USER in the code, it won't work.  Just returns an empty
string. <scratches head>  At this point that is a non-issue tho.
Thanks again.

-- 
<Wildman> GNU/Linux user #557453



More information about the Python-list mailing list