简体   繁体   English

在Python中执行从文件读取为字符串的复杂Shell命令

[英]Executing A complex Shell command read as String from a File in Python

I have a configuration file where user can specify a set of shell commands. 我有一个配置文件,用户可以在其中指定一组shell命令。 Commands are basically a chain of pipe-separated shell commands. 命令基本上是由管道分隔的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

I am able to read the commands in my Python scripts. 我能够读取Python脚本中的命令。 My question is how will I be able to run these read command strings in Python and get the output. 我的问题是我将如何在Python中运行这些读取的命令字符串并获得输出。

Any solution with subprocess , plumbum , sh will be acceptable. 任何带有subprocessplumbumsh解决方案都是可以接受的。

Use subprocess.check_output () 使用subprocess.check_output ()

output = subprocess.check_output(output)

Something to be aware of is that unlike the other subprocess commands, a subprocess.CalledProcessError will be raised if a non-zero error code is returned. 需要注意的是,与其他子流程命令不同,如果返回非零错误代码,则会引发subprocess.CalledProcessError。


You shouldn't need to do this, but in case it comes in handy to somebody out there, I did run into an experience once where for some reason the above solution did not work, and so, instead, I did the following. 您不需要这样做,但是万一它派上用场的话,我确实遇到了一次经验,由于某种原因上述解决方案不起作用,因此,我做了以下工作。

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM