这是我的copy.py:
from subprocess import call call("copy p2.txt p3.txt")
如果在命令提示符下使用
copy p2.txt p3.txt
它复制罚款。
但是当我使用python copy.py
它给了我:
Traceback (most recent call last): File "copy.py", line 2, in <module> call("copy p2.txt p3.txt") File "C:\Python27\lib\subprocess.py", line 493, in call return Popen(*popenargs, **kwargs).wait() File "C:\Python27\lib\subprocess.py", line 679, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 896, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified
如果我把python调用replace成xcopy,它可以正常工作。
为什么会这样?
当像subprocess.call()
这样的shell命令,你也需要指定shell=True
。
from subprocess import call call("copy p2.txt p3.txt", shell=True)
在这种情况下,您需要使用shell=True
的原因是,Windows中的copy
命令实际上不是可执行文件,而是shell的内置命令(如果内存正常运行)。 另一方面, xcopy
是一个真正的可执行文件(在%WINDIR%\System32
,通常在%PATH%
),因此可以在cmd.exe
外部调用它。
在这个特定的例子中, shutil.copy
或shutil.copy2
可能是可行的选择。
请注意,使用shell=True
可能会导致安全隐患,或者如文档所述:
警告:使用
shell=True
可能是安全隐患。 有关详细信息,请参阅常用参数下的警告。