【问题标题】:Executing A complex Shell command read as String from a File in Python执行从 Python 文件中读取为字符串的复杂 Shell 命令
【发布时间】:2017-04-07 05:46:40
【问题描述】:

我有一个配置文件,用户可以在其中指定一组 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 中运行这些读取命令字符串并获得输出。

任何带有subprocessplumbumsh 的解决方案都可以接受。

【问题讨论】:

  • 顺便说一句,您的管道看起来像是想要成为小型 Awk 脚本。 CMD1 = awk -F: '/SomeOtherString/ && /XX/ { s=$9; sub(/,.*/, "", s); print s }'CMD2 = awk -F: '/SomeOtherString { s=$9; sub(/][^],]*,.*/, "", s); sub(/^[^[]*\[/, "", s); } END { print s }'
  • @tripleee 是的,它也可以有 awk 命令:grep "Something" ${LOGFILE}|tail -1|awk -F"=" '{ print $3 }'
  • 我的意思是,您的脚本可能应该完全用 Awk 编写,或者至少主要用 Awk 编写。一旦管道中有两个或三个以上的 grepcuttail 命令,您应该开始思考。当然,你最新的例子写得更好awk -F= '/Something/ { s=$3 } END { print s }' "$LOGFILE"
  • 谢谢 .. 如果我将命令链作为字符串传递给 python 子进程,我们将更倾向于知道会发生什么问题

标签: python bash shell subprocess plumbum


【解决方案1】:

使用subprocess.check_output()

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

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    相关资源
    最近更新 更多