我正在编写一个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。
最佳答案
造成这种情况的原因有很多:
copy
是内置的 Windows shell,它不是可执行文件。您必须使用shell=True
- 您的
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/