gpt4 book ai didi

linux - 如何在 python 中将 '>' 作为参数传递给终端

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:46 24 4
gpt4 key购买 nike

我想知道你是否可以帮我解决一个问题:

在 python 中,我一直在尝试将“>”赋予 subprocess.Popen([]) 或 subprocess.call([]),但不知何故,它改变了在终端中输入的方式。一个例子。

终端命令:

iperf -s -u -y C > data.csv

Python代码:

import subprocess as sub

sub.Popen(['iperf', '-s', '-u', '-y', 'C', '>', 'data.csv'])

sub.Popen(['{iperf', '-s', '-u', '-y', 'C}', '>', 'data.csv'])

当我在终端中运行第一个命令时,它会执行得很好,但是当我执行第二个命令时,它会完全忽略“>”和“data.csv”:

$ python test.py
iperf: ignoring extra argument -- >
iperf: ignoring extra argument -- data.csv

第三个命令返回:

$ python test.py 
Traceback (most recent call last):
File "test.py", line 3, in <module>
sub.call(['{iperf', '-s', '-u', '-y', 'C}', '>', 'data.csv'])
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

我已经尝试在 DuckDuckGo 和 Google 上搜索这个问题,但我找不到答案,因为他们不会解释 '>' 符号,即使用作“>”也是如此。

我期待着您的回答,在此先感谢您!

最佳答案

> 由 shell 而非程序解释。由于默认情况下 subprocess 不使用 shell,因此 > 直接传递给程序。使用 shell=True 可能有效,但要重定向 stdout,您应该使用 stdout 参数。

例如,你可以使用

import subprocess

with open('data.csv', 'w') as f:
subprocess.Popen(['iperf', '-s', '-u', '-y', 'C'], stdout=f)

关于linux - 如何在 python 中将 '>' 作为参数传递给终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com