[英]How to pass a shell command into Python script
Hello I would like to pass a shell command in the linux terminal to variable into Python script:您好,我想将 linux 终端中的 shell 命令传递到 Python 脚本中:
Here is the command in linux:这是linux中的命令:
echo "azerty"
My python script would be a very simple script that print the result.我的 python 脚本将是一个打印结果的非常简单的脚本。 The name of the script is test.py脚本的名称是 test.py
In my terminal I would use:在我的终端中,我会使用:
echo "azerty" | ./test.py
and It would return:它会返回:
azerty
Maybe you can hel.也许你可以帮助。 Thanks谢谢
When you perform some_command | other_command
当你执行some_command | other_command
some_command | other_command
in any POSIX shell, what it actually does is that it redirects the standard output (called stdout) of some_command
to the standard input (called stdin) of other_command
.在任何 POSIX shell 中的some_command | other_command
,它实际上所做的是将 some_command 的标准some_command
(称为 stdout)重定向到other_command
的标准输入(称为 stdin)。 In python you can access the standard input using the sys
module.在 python 中,您可以使用sys
模块访问标准输入。
From the official python documentation about sys.stdin
:从关于sys.stdin
的官方 python 文档:
These streams are regular text files like those returned by the open() function.这些流是常规文本文件,如 open() function 返回的那些。
Reading the standard input in python is as simple as that:读取 python 中的标准输入就这么简单:
import sys
content = sys.stdin.read()
print(content)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.