【问题标题】:subprocess.call() in windows 10 returns an error that it can't find the fileWindows 10 中的 subprocess.call() 返回找不到文件的错误
【发布时间】:2018-09-16 16:27:02
【问题描述】:

我正在编写一个 unix 脚本,该脚本需要一些修改才能在 Windows 10 下工作。该脚本使用子进程使用 DOS 命令执行文件操作。具体来说,使用 subprocess 将文件从目录复制到当前目录的语句会返回错误消息。 正确的DOS命令是

copy "D:\tess\catalog files\TIC55234031.fts" .

然而,

ref_fits_filename="D:\TESS\catalog files\TIC55234031.fts"

subprocess.call(['copy ', ref_fits_filename,' .'])         # copy the ref fits file to here

旨在执行完全相同的操作,出错了:

Traceback(最近一次调用最后一次):
  文件“EBcheck.py”,第 390 行,在
    subprocess.call(['copy ', ref_fits_filename,' .']) # 复制 ref 拟合文件到这里
  文件“C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py”,第 267 行,调用中
    使用 Popen(*popenargs, **kwargs) 作为 p:
  文件“C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py”,第 709 行,在 __init__
    恢复信号,开始新会话)
  _execute_child 中的文件“C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py”,第 997 行
    启动信息)
FileNotFoundError: [WinError 2] 系统找不到指定的文件

显然,一定有一个微妙的语法错误或我没有想到的问题导致了问题。 Windows 10下的Python编程专家是否在这个论坛上澄清了这个问题? 这里使用的 Python 版本是最近的 Python 3.6.4。

【问题讨论】:

  • copy 是 shell 内置的。为此,您需要shell=True。另外,您的副本 arg 中有一个空格。

标签: python python-3.x subprocess


【解决方案1】:

原因有很多:

  1. copy 是内置的 Windows shell,它不是可执行文件。你必须使用shell=True
  2. 您的 subprocess.call(['copy ', ref_fits_filename,' .']) 在参数中有空格

所以你可以这样做:

subprocess.call(['copy', ref_fits_filename,'.'],shell=True)

但最pythonic的方法是放弃所有这些并使用shutil.copy

import shutil
shutil.copy(ref_fits_filename,".")

作为奖励,如果副本出错,您会得到一个干净的 python 异常。

除此之外:在将 Windows 路径定义为文字时始终使用原始前缀:

ref_fits_filename = r"D:\tess\catalog files\TIC55234031.fts"

(我猜您将tess 大写为TESS 以解决\t 是制表字符的事实:))

【讨论】:

  • r"C:\Some Path With Space\myfile.txt" 足以处理我们想要做的空间填充路径r'"C:\Some Path With Space\myfile.txt"' 吗?
  • 空间不是这里的问题。问题是像\t\n 这样的转义序列,这解释了为什么不知情的 Windows 用户倾向于将所有路径都大写(尽管 \U 失败)
猜你喜欢
  • 2018-10-26
  • 2011-03-02
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多