python - Windows 10 中的 subprocess.call() 返回找不到文件的错误

标签 python python-3.x subprocess

我正在编写一个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 (most recent call last):
  File "EBcheck.py", line 390, in 
    subprocess.call(['copy ', ref_fits_filename,' .'])         # copy the ref fits file to here
  File "C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 267, in call
    with Popen(*popenargs, **kwargs) as p:
  File "C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

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

最佳答案

造成这种情况的原因有很多:

  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 是制表字符的事实:))

关于python - Windows 10 中的 subprocess.call() 返回找不到文件的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49696238/

相关文章:

python - 使用 Python 在 Windows 上传递管理权限

python - 在 Python 中打印浮点值(Mapbox 地理坐标)

python - 我想在应用程序关闭时保存 PyQt5 设置

python - django 管理 url 重定向到自定义 url

Python setuptools 入口点和子应用程序作为子进程

python - 通知 python 脚本进程已完成

python - Flake8 抛出 B008 fastapi 数据类型定义

python-3.x - 模块未找到错误 : No module named '_sqlite3'

python - 计算 csv 中 "NaN"(不是零或空白)的数量

python - 如何迭代模糊比的最大值并导出到新的 CSV 文件