Calling Bash Command From Python
Jon Ribbens
jon+usenet at unequivocal.eu
Mon Oct 31 04:13:54 EDT 2016
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"]
More information about the Python-list
mailing list