我在bash(Linux)上测试了以下命令,它运行正常:
awk '/string1\/parameters\/string2/' RS= myfile | grep Value | sed 's/.*"\(.*\)"[^"]*$/\1/'
现在我必须在python脚本中调用它,而string1和string2是python变量。
我尝试使用os.popen,但我没有弄清楚如何连接字符。
有任何想法如何解决这个问题?
提前感谢您的帮助!
答案 0 :(得分:0)
您可以使用subprocess.check_output()
将变量替换为命令,使用format():
cmd = """awk '/{}\/parameters\/{}/' RS= myfile | grep Value | sed 's/.*"\(.*\)"[^"]*$/\1/'""".format('string1', 'string2')
cmd_output = subprocess.check_output(cmd, shell=True)
但请注意有关在引用文档中使用shell=True
的警告。
另一种方法是使用Popen()
:
import shlex
from subprocess import Popen, PIPE
awk_cmd = """awk '/{}\/parameters\/{}/' RS= myfile""".format('s1', 's2')
grep_cmd = 'grep Value'
sed_cmd = """sed 's/.*"\(.*\)"[^"]*$/\1/'"""
p_awk = Popen(shlex.split(awk_cmd), stdout=PIPE)
p_grep = Popen(shlex.split(grep_cmd), stdin=p_awk.stdout, stdout=PIPE)
p_sed = Popen(shlex.split(sed_cmd), stdin=p_grep.stdout, stdout=PIPE)
for p in p_awk, p_grep:
p.stdout.close()
stdout, stderr = p_sed.communicate()
print stdout
答案 1 :(得分:0)
你可以与Popen replace shell pipeline:
from subprocess import PIPE,Popen
from shlex import split
p1 = Popen(split("awk /string1\/parameters\/string2 RS=myfile"), stdout=PIPE)
p2 = Popen(["grep", "Value"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
p3 = Popen(split("""sed 's/.*"\(.*\)"[^"]*$/\1/'"""), stdin=p2.stdout, stdout=PIPE)
p2.stdout.close() # Allow p2 to receive a SIGPIPE if p3 exits.
output = p3.communicate()[0]