python:字符串作为子命令的标准输入

标签 python shell

我有一个 python 脚本,需要在其中调用 shell 命令。 shell 命令可以接受来自文件或标准输入的输入。

在我的脚本中,输入存储在变量中。调用命令的正确方法是什么?如果重要的话,shell 命令不会产生输出。

我知道我可以将变量的内容写入文件并以文件作为参数调用命令,但这似乎不优雅。当然,还有更好的方法。

谁能告诉我这是什么?谢谢。

最佳答案

您可以使用subprocess模块。

import subprocess
process = subprocess.Popen(["Mycommand", "with", "arguments"], stdin=subprocess.PIPE)
process.communicate("My text")

关于python:字符串作为子命令的标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261126/

相关文章:

python - 使用 imaplib 在 gmail 中删除电子邮件时出现问题

Python - Pandas 索引和选择

bash - shell脚本中的while循环条件

shell - 如何使用 Shell 脚本修改 job.properties 文件并运行 Oozie 脚本?

linux - 使用 Zoidberg 或 Term::Shell ( Perl 模块 ) 哪一个更好地在 Perl 中实现自定义 shell?

bash - 来自 bash 变量的 Linux whiptail/dialog 参数错误

linux - unix shell 中 echo 和 @echo 的区别

python - 预处理后的名称特征重要性图

python - 在一组 Pandas 数据框中提取具有最大值的行

python - 将 ndarray 转换为灰度