1

I am trying to use command substitution for building a linux command from a python script, but am not able to get the following simple example to work:

LS="/bin/ls -l"
FILENAME="inventory.txt"

cmd = "_LS _FILENAME "
ps= subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print output

Thanks!

JB

1 Answer 1

0

Use string substitution:

cmd = '{} {}'.format(LS, FILENAME)

or (in Python2.6):

cmd = '{0} {1}'.format(LS, FILENAME)

import subprocess
import shlex

LS="/bin/ls -l"
FILENAME="inventory.txt"

cmd = '{} {}'.format(LS, FILENAME)    
ps = subprocess.Popen(shlex.split(cmd),
                      stdout = subprocess.PIPE,
                      stderr = subprocess.STDOUT)
output, err = ps.communicate()
print(output)

Or, using the sh module:

import sh
FILENAME = 'inventory.txt'
print(sh.ls('-l', FILENAME, _err_to_out=True))
Sign up to request clarification or add additional context in comments.

2 Comments

This worked very nicely. For some reason I thought command substitution for python would be under the same title and not Formatting. Thanks!
Be wary of security when doing it like this. It's way too easy to add shell injection due to improper quoting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.