【发布时间】:2018-03-26 02:33:35
【问题描述】:
在python中,当我执行命令时
cmd = ['head', '-7', 'rres17.txt', '>', 'x']
subprocess.run(cmd)
我收到错误消息
head: cannot open ‘>’ for reading: No such file or directory
head: cannot open ‘x’ for reading: No such file or directory
当我执行命令时
cmd = "head -7 rres17.txt > x"
subprocess.run(cmd)
我收到错误消息
FileNotFoundError: [Errno 2] No such file or directory: 'head -7 rres17.txt > x'
我正在使用 python 版本 3.5.2。如何让子流程正确 执行此命令,文档似乎表明它应该的方式?谢谢。
编辑:
以下命令有效:
cmd = ['head', '-7', 'rres17.txt']
with open("x", "wb") as out: subprocess.Popen(cmd, stdout=out)
谢谢大家。
【问题讨论】:
-
尝试将 'rres17.txt' 更改为完整路径。
-
@eyllanesc,当我更改为完整路径时,我得到了同样的错误。
-
>语法是 shell 处理的东西,而不是真正应该进入执行命令的东西。 -
你需要使用
subprocess的输出重定向工具,而不是shell语法。
标签: python subprocess file-not-found