PyWin32 是要走的路——但是如何使用它呢?一种方法是从您遇到的具体问题开始并尝试解决它。 PyWin32 为 Win32 API 函数提供了很多绑定,你必须首先选择一个特定的目标。
在我的 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)一起使用。从这个例子中,你可以对如何使用这个库有一个“一般的感觉”。