如何在 Python 中使用 win32 API?
最好和最简单的方法是什么?
可以举一些例子吗?
最佳答案
PyWin32 是要走的路——但如何使用它?一种方法是从您遇到的具体问题开始并尝试解决它。 PyWin32 为 Win32 API 函数提供了很多绑定(bind),你必须首先选择一个特定的目标。
在我的 Python 2.5 安装(Windows 上的 ActiveState)中,win32 包有一个 Demos 文件夹,其中包含库各个部分的示例代码。
例如,这里是 CopyFileEx.py:
import win32file, win32api
import os
def ProgressRoutine(TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred,
StreamNumber, CallbackReason, SourceFile, DestinationFile, Data):
print Data
print TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred, StreamNumber, CallbackReason, SourceFile, DestinationFile
##if TotalBytesTransferred > 100000:
## return win32file.PROGRESS_STOP
return win32file.PROGRESS_CONTINUE
temp_dir=win32api.GetTempPath()
fsrc=win32api.GetTempFileName(temp_dir,'cfe')[0]
fdst=win32api.GetTempFileName(temp_dir,'cfe')[0]
print fsrc, fdst
f=open(fsrc,'w')
f.write('xxxxxxxxxxxxxxxx\n'*32768)
f.close()
## add a couple of extra data streams
f=open(fsrc+':stream_y','w')
f.write('yyyyyyyyyyyyyyyy\n'*32768)
f.close()
f=open(fsrc+':stream_z','w')
f.write('zzzzzzzzzzzzzzzz\n'*32768)
f.close()
operation_desc='Copying '+fsrc+' to '+fdst
win32file.CopyFileEx(fsrc, fdst, ProgressRoutine, operation_desc, False, win32file.COPY_FILE_RESTARTABLE)
它展示了如何将 CopyFileEx 函数与其他一些函数(例如 GetTempPath 和 GetTempFileName)一起使用。从这个例子中,您可以对如何使用这个库有一个“总体感觉”。
关于python - 如何在 Python 中使用 Win32 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1025029/