python-运行shell命令,获取stdout和stderr作为变量,但请躲藏在用户中吗?
我想让我的Python脚本运行Linux Shell命令并将输出存储在变量中,而不会向用户显示命令的输出。我已经使用OS.System
,subprocess.check_output
,subprocess.run
,subprocess.popen
和OS.Popen
没有运气。
我当前的方法是运行OS.System(“ LS -L&>/tmp/test_file”)
,因此命令stdout和stderr被管道到/tmp/test_file
,然后我的Python代码将文件读为变量,然后将其删除。
是否有更好的方法来这样做,以便我可以将命令输出直接发送到变量中,而无需创建和删除文件,而是将其隐藏在用户中?
I would like to have my Python script run a Linux shell command and store the output in a variable, without the command's output being shown to the user. I have tried this with os.system
, subprocess.check_output
, subprocess.run
, subprocess.Popen
, and os.popen
with no luck.
My current method is running os.system("ls -l &> /tmp/test_file")
so the command stdout and stderr are piped to /tmp/test_file
, and then I have my Python code read the file into a variable and then delete it.
Is there a better way of doing this so that I can have the command output sent directly into the variable without having to create and delete a file, but keep it hidden from the user?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@codester_09的解决方案在技术上是正确的,但仅回答了一半的问题,并且没有显示如何将输出分配给变量。
STDOUT和STDERR的结果是
bytes
对象,因此,如果您想将它们作为字符串处理,则需要对其进行解码:The solution by @codester_09 is technically correct but only answers half the question and does not show how to assign the output to a variable.
The results of stdout and stderr are
bytes
objects so you will need to decode them if you want to handle them as strings, for example:您可以使用 功能。
@Ashley Kleynhans说的一个更新
。或stderr,因为在
运行
方法中,您可以传递一个参数以将返回数据作为字符串获取,即text = true
You can use the
subprocess.run
function.One update as @Ashley Kleynhans say
For this, you do not need to
decode
stdout or stderr because in therun
method you can pass one more argument to get the return data as a string, which istext=True