【问题标题】:How to pass a shell command into Python script如何将 shell 命令传递给 Python 脚本
【发布时间】:2021-02-19 19:30:47
【问题描述】:

您好,我想将 linux 终端中的 shell 命令传递给 Python 脚本中的变量:

这是linux中的命令:

echo "azerty"

我的 python 脚本将是一个打印结果的非常简单的脚本。脚本名称为 test.py

在我的终端中我会使用:

echo "azerty" | ./test.py

它会返回:

azerty

也许你能帮上忙。谢谢

【问题讨论】:

  • 你了解| 的作用吗?你搜索了什么?
  • 是的,先在终端打印回显然后运行脚本Python
  • 我想通过 Python 脚本打印终端的输出

标签: python-3.x linux terminal echo


【解决方案1】:

当您在任何 POSIX shell 中执行some_command | other_command 时,它实际上所做的是将some_command 的标准输出(称为stdout)重定向到other_command 的标准输入(称为stdin)。在 python 中,您可以使用sys 模块访问标准输入。

来自official python documentation关于sys.stdin

这些流是常规文本文件,类似于 open() 函数返回的那些。

在python中读取标准输入就这么简单:

import sys
content = sys.stdin.read()
print(content)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-14
    • 2020-01-03
    • 1970-01-01
    • 2022-01-23
    • 2015-01-21
    • 2011-02-03
    • 2019-07-02
    • 2022-10-04
    相关资源
    最近更新 更多