Perl-like backtick in Python

Fernando Pérez fperez528 at yahoo.com
Thu May 2 15:51:40 EDT 2002


Tom Verbeure wrote:

> Hi All,
> 
> In Perl i can do something like this:
> 
> $str = `cat myfile.in`;
> 
> Basically the string that is surrounded by the backticks is executed
> by a shell and the stdout is returned as a string.
> 
> In the python library, there is spawn*, exec* and system, but the
> return the exit status of the command, not the output. Any suggestions
> about who to do this?
> 
> Thanks,
> Tom

These are my two mini-idioms to do that conveniently (import modules as 
needed: os, commands).


def xsys(cmd,verbose=0,debug=0,head=''):
    """Execute a system command, but optionally print it.
    With debug=1, only prints."""

    stat = 0
    if verbose or debug: print head+cmd
    if not debug: stat = os.system(cmd)
    return stat



def bq(cmd,verbose=0,debug=0,head=''):
    """Dummy substitute for perl's backquotes.
    Executes a command and returns the output.

    Accepts same arguments as xsys.
    """
    if verbose or debug: print head+cmd
    if not debug:
        output = commands.getoutput(cmd)
        return output

Cheers,

f.



More information about the Python-list mailing list