【问题标题】:python subprocess no such filepython子进程没有这样的文件
【发布时间】: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


【解决方案1】:

您不能将标准输出重定向到这样的文件,您需要使用subprocess.run 并重定向到管道。

piping output of subprocess.Popen to files

例如:

import subprocess
import io

with io.open('x', mode='wb') as fd:
    subprocess.run(['head', '-7', 'rres17.txt'], stdout=fd)

【讨论】:

  • 我仍然遇到同样的错误。将 [code] 与 open("x", "wb") 作为 out: subprocess.Popen(cmd, stdout=out) code 并删除 shell 重定向会产生相同的错误。
猜你喜欢
  • 2021-06-11
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 2017-01-19
  • 2019-01-17
  • 1970-01-01
相关资源
最近更新 更多