popen()no do no the stdout将stdout重定向到文件

发布于 2025-01-29 19:36:53 字数 1490 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心清如水 2025-02-05 19:36:53

使用此最低信息,我无法为您提供很多帮助,但我建议您做类似的事情:

with open("fout.txt","a") as out:
    subprocess.Popen("starting_cmd",stdout=out)
  • 该过程不需要阅读信息,因此我们不需要在阅读模式下打开文件(这是最好的练习以将对文件的访问限制为仅到必要的内容)。因此,您可以将W+替换为Wa(为了附加fout.txt)。
  • 带有的用于上下文,以确保当out脱离范围时,该文件已关闭,这有可能有助于使结果在文件中可见。

这是一个有效的例子(在Python3中):

import subprocess
with open("fout.txt", "a") as out:
    subprocess.Popen("ls", stdout=out)

With this minimum information I can't help you a lot but I'll suggest you do something like this :

with open("fout.txt","a") as out:
    subprocess.Popen("starting_cmd",stdout=out)
  • The process don't need to read info so we don't need to open the file in reading mode (and it's a best practice to restrain the access to a file to only what's necessary). You could therefore replace w+ with just w or a (to append fout.txt).
  • The with is for context managing to be sure the file is closed when out goes out of scope, which can potentially help to make the result visible in the file.

Here's a working example (in python3) :

import subprocess
with open("fout.txt", "a") as out:
    subprocess.Popen("ls", stdout=out)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文