Python中对Linux命令的命令替换

1 投票
1 回答
2626 浏览
提问于 2025-04-17 15:25

我正在尝试在一个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

1 个回答

0

使用 字符串替换

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))

撰写回答