[英]Executing A complex Shell command read as String from a File in Python
我有一个配置文件,用户可以在其中指定一组shell命令。 命令基本上是由管道分隔的Shell命令组成的链。
CMD1 = grep "SomeOtherString" | grep "XX" | cut -d":" -f9 | cut -d"," -f1
CMD2 = grep "SomeOtherString" | tail -1| cut -d":" -f9 | cut -d"," -f1 | cut -d"[" -f2 | cut -d"]" -f1
我能够读取Python脚本中的命令。 我的问题是我将如何在Python中运行这些读取的命令字符串并获得输出。
任何带有subprocess
, plumbum
, sh
解决方案都是可以接受的。
output = subprocess.check_output(output)
需要注意的是,与其他子流程命令不同,如果返回非零错误代码,则会引发subprocess.CalledProcessError。
您不需要这样做,但是万一它派上用场的话,我确实遇到了一次经验,由于某种原因上述解决方案不起作用,因此,我做了以下工作。
stdout_fh = io.StringIO()
stderr_fh = io.StringIO()
with redirect_stderr(stderr_fh):
with redirect_stdout(stdout_fh):
subprocess.run(command, shell=True)
stderr = stderr_fh.getvalue()
stdout = stderr_fh.getvalue()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.