我正在关注这个教程here,其中调用windows API的CopyFile函数对我来说不起作用。这是我正在使用的代码(只是更改了用户名)
from ctypes import *
CopyFile = windll.kernel32.CopyFileA
CopyFile("C:\Windows\System32\calc.exe", "C:\\Users\legion\Desktop\calc.exe", False)
我尝试更改参数,文件路径,我尝试将同一文件更改为同一目录,将False更改为True,以便我可能会收到错误或提示该文件已存在。它只是不起作用。如果你还没有和Ctypes一起工作(比如我)并且不知道答案,请尝试在你的机器上试用这个片段。
答案 0 :(得分:1)
我看到的1 st 事情是,路径中的某些反斜杠 es不会被转义。在这种特殊情况下它不会成为一个问题,但总是逃避它们会更好。
我稍微修改了你的代码( code0.py ):
#!/usr/bin/env python3
import sys
import os
from ctypes import windll
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
src = r"C:\Windows\System32\calc.exe"
dst = os.path.join(os.getcwd(), "calc.exe") # Change this to your original path
kernel32_dll = windll.kernel32
copy_file_a = kernel32_dll.CopyFileA
copy_file_w = kernel32_dll.CopyFileW
reta = copy_file_a(src, dst, False)
retw = copy_file_w(src, dst, False)
print("CopyFileA returned: {:d}\nCopyFileW returned: {:d}\n".format(reta, retw))
<强>输出强>:
E:\Work\Dev\StackOverflow\q048927571>"e:\Work\Dev\VEnvs\py27x64_test\Scripts\python.exe" code0.py Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32 CopyFileA returned: 1 CopyFileW returned: 0 E:\Work\Dev\StackOverflow\q048927571>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code0.py Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 CopyFileA returned: 0 CopyFileW returned: 1
备注强>:
如果函数成功,则返回值为非零值。
char *
),而在 Python 3 中它们是在 Win 上 Unicode ( 16位(wchar_t *
)我们有失败的原因,但我们还没有完成。这是一个更详细的示例( code1.py ):
#!/usr/bin/env python3
import sys
import os
from ctypes import windll, c_char_p, c_wchar_p, c_int
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
src = r"C:\Windows\System32\calc.exe"
dst = os.path.join(os.getcwd(), "calc.exe")
kernel32_dll = windll.kernel32
copy_file_a = kernel32_dll.CopyFileA
copy_file_a.argtypes = (c_char_p, c_char_p, c_int)
copy_file_a.restype = c_int
copy_file_w = kernel32_dll.CopyFileW
copy_file_w.argtypes = (c_wchar_p, c_wchar_p, c_int)
copy_file_w.restype = c_int
reta = copy_file_a(src.encode(), dst.encode(), False)
retw = copy_file_w(src, dst, False)
print("CopyFileA returned: {:d}\nCopyFileW returned: {:d}\n".format(reta, retw))
备注强>:
<强>输出强>:
E:\Work\Dev\StackOverflow\q048927571>"e:\Work\Dev\VEnvs\py27x64_test\Scripts\python.exe" code1.py Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32 CopyFileA returned: 1 CopyFileW returned: 1 E:\Work\Dev\StackOverflow\q048927571>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code1.py Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 CopyFileA returned: 1 CopyFileW returned: 1