Calling Bash Command From Python

Chris Angelico rosuav at gmail.com
Mon Oct 31 00:31:27 EDT 2016


On Mon, Oct 31, 2016 at 3:19 PM, Wildman via Python-list
<python-list at python.org> 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

Are you able to run that command without a password? sudo might be
attempting to open the console, failing, and aborting the command. Is
anything being printed to stderr?

ChrisA



More information about the Python-list mailing list