如何在Python中向终端传递'>'作为参数

0 投票
2 回答
711 浏览
提问于 2025-04-20 09:19

我想请你帮我解决一个问题:

在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上搜索这个问题,但找不到答案,因为它们不会解释'>'这个符号,即使是用">"的形式。

期待你们的回答,非常感谢!

2 个回答

1

把命令作为一个字符串传递给 subprocess,并通过设置 shell=True 来告诉它这是一个 shell 命令:

源代码

import subprocess

print subprocess.call([
    "echo beer > zoot"
], shell=True)

输出

0
5

> 这个符号是由命令行的外壳(shell)来解释的,而不是由程序本身来处理。因为子进程默认不使用外壳,所以 > 会直接传给程序。如果你使用 shell=True,可能会有效果,但如果想要重定向 stdout(标准输出),你应该使用 stdout 这个参数。

比如,你可以这样使用:

import subprocess

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

撰写回答