作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想知道你是否可以帮我解决一个问题:
在 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/
我是一名优秀的程序员,十分优秀!