Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: execute bash builtins in python

24 views
Skip to first unread message

Steve Holden

unread,
Mar 12, 2010, 8:15:49 AM3/12/10
to pytho...@python.org
alex goretoy wrote:
> hi,
> i'm trying to write a section of my program that needs to run bash
> builtin alias and declare, i've googled and tried every type of example
> i could find no to avail. this is what I've tried below and it doesn't
> work, is there a way for me to execute a bah builin from python? what i
> need is to take alias output and pipe it to another command with python
> and return the results to a string or list.
>
>>>> p1=Popen(["alias"],stdout=PIPE)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "/usr/lib/python2.6/subprocess.py", line 621, in __init__
> errread, errwrite)
> File "/usr/lib/python2.6/subprocess.py", line 1126, in _execute_child
> raise child_exception
> OSError: [Errno 2] No such file or directory
>
> if i add shell=True i get empty string and no thins error message
>
>>>> p1=Popen(["alias"],stdout=PIPE,shell=True)
>>>> p1
> <subprocess.Popen object at 0xb7589a4c>
>>>> p1.stdout.read()
> ''
>
> thank you,
> -Alex Goretoy
>
For shell=True I believe you should provide the command as a single
string, not a list of arguments.

>>> p1 = Popen("alias", stdout=PIPE, shell=True)
>>>

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

Steve Holden

unread,
Mar 13, 2010, 8:08:24 AM3/13/10
to pytho...@python.org
alex goretoy wrote:
> I found this to be even better; maybe someone will find this useful, who
> knows.
> just export PS1, duh
> Popen(["bash -c 'export PS1='python'; source
> $HOME/.bashrc;alias'"],shell=True,stdout=PIPE).stdout.read()
>
Try using an interactive shell:

>>> from subprocess import *
>>> p1 = Popen("bash -i -c alias", stdout=PIPE, shell=True)
>>> p1.stdout.read()
"alias ls='ls --color=auto'\n"

Nobody

unread,
Mar 17, 2010, 11:44:34 AM3/17/10
to
On Fri, 12 Mar 2010 08:15:49 -0500, Steve Holden wrote:

> For shell=True I believe you should provide the command as a single
> string, not a list of arguments.

Using shell=True with an argument list is valid.

On Unix, it's seldom what you want: it will invoke /bin/sh to execute the
first argument with $1, $2, ... set from the remaining arguments.

On Windows, a list is converted to a string in the same manner regardless
of the value of the "shell" argument. Specifying shell=True causes the
command string to be executed via "cmd /c ...". This allows the "program"
to be a script, whereas shell=False requires the program to be a binary
executable.

0 new messages