Friday, November 1, 2013

What is the Python equivalent of perl's backtics?

One of my favorite features in perl is backtics:  They execute something on the command line, and load the output as a variable:
>  @config_filenames = `ls *.config`;     # loads all the config files in this directory

Easy, huh?  Here's the equivalent in python.  Not as short, but it works:
include commands
dothis = "ls *.config"
temp = commands.getoutput(dothis) 



2 comments:

  1. Cool, I didn't know about the commands module. However, it's been deprecated.
    The equivalent with subprocess:
    import subprocess # note- not include!
    dothis = 'ls *.config'
    temp = subprocess.check_output(dothis.split())

    but it gives nastier error messages when it fails, I think

    ReplyDelete
  2. Update: Need to have "shell=True" if there's an asterisk:
    temp = subprocess.check_output(dothis, shell=True).split()

    ReplyDelete