简体   繁体   English

Python3:os.system 不重定向标准输出

[英]Python3: os.system not redirecting stdout

As mentioned in the title.如标题所述。 I have this in my code:我的代码中有这个:

os.system("./vpr/vpr " + config + " " + file_name + " --seed " + str(seed) + " &> " + str(bench_name) + "-" + str(seed) + ".stdout")

Which has a lot of variables, but it simply evaluates to this (I know for sure because I have a print statement right before the os.system line):它有很多变量,但它只是简单地评估为这个(我肯定知道,因为我在os.system行之前有一个打印语句):

./vpr/vpr vpr/k6_N10_40nm.xml vpr/blif/clma.blif --seed 0 &> clma-0.stdout

The command actually runs fine, but the redirection does not!该命令实际上运行良好,但重定向没有! The file clma-0.stdout gets created but remains empty, and I still get the entire stdout on my terminal.文件clma-0.stdout被创建但仍然是空的,我仍然在我的终端上获得整个标准输出。

What is the solution for that?什么是解决方案? What am I doing wrong?我究竟做错了什么? I'm using python-3.7 on Ubuntu 19.10我在 Ubuntu 19.10 上使用 python-3.7

Thanks.谢谢。

I'm not sure why exactly, but it seems like os.system is using Dash (Ubuntu's default scripting shell), not Bash, so &> is not supported.我不确定为什么会这样,但似乎os.system使用的是 Dash(Ubuntu 的默认脚本外壳),而不是 Bash,因此不支持&> What happens instead is the command is backgrounded, and the file is truncated.相反,命令是后台运行的,并且文件被截断。 That is, command &> filename is equivalent to command &; > filenamecommand &> filename等价于command &; > filename command &; > filename . command &; > filename

To fix it you could simply use the equivalent redirection, > filename 2>&1 .要修复它,您可以简单地使用等效的重定向> filename 2>&1

I think that's because you are trying to do it using system command, not Bash which supports these I/O redirection flags.我认为这是因为您正在尝试使用系统命令来执行此操作,而不是使用支持这些 I/O 重定向标志的 Bash。

Try this one with shell=True https://docs.python.org/2/library/subprocess.html#subprocess.call试试这个shell=True https://docs.python.org/2/library/subprocess.html#subprocess.call

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM