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 回答