1

PythonスクリプトからLinuxコマンドを構築するためにコマンド置換を使用しようとしていますが、次の簡単な例を機能させることができません:

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

ありがとう!

JB

4

1 に答える 1

1

文字列置換を使用:

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

または (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)

または、sh モジュールを使用します。

import sh
FILENAME = 'inventory.txt'
print(sh.ls('-l', FILENAME, _err_to_out=True))
于 2013-02-10T15:27:11.983 に答える