如何在python中使用win32 API?

kol*_*vra 52 python api winapi

如何在Python中使用win32 API?
最好和最简单的方法是什么?
你能举一些例子吗?

Eli*_*sky 38

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)
Run Code Online (Sandbox Code Playgroud)

它显示了如何将CopyFileEx函数与其他一些函数一起使用(例如GetTempPath和GetTempFileName).从这个例子中,您可以获得如何使用此库的"一般感觉".

  • 样式备注:3`open(fn,'w').写入('data')CPython中的行与9'open,write,close'行相同的消息. (3认同)

Ale*_*lli 23

@chaos提到的PyWin32可能是最受欢迎的选择; 另一种选择是ctypes,它是Python标准库的一部分.例如,print ctypes.windll.kernel32.GetModuleHandleA(None)将显示当前模块(EXE或DLL)的模块句柄.使用ctypes的获得在Win32 API的一个更广泛的例子是在这里.

  • 该示例的链接对我不起作用. (3认同)

Tab*_*res 5

您可以在win32 Python中使用的重要功能是消息框,这是OK或Cancel的经典示例.

result = win32api.MessageBox(None,"Do you want to open a file?", "title",1)



  if result == 1:
     print 'Ok'
  elif result == 2:
     print 'cancel'
Run Code Online (Sandbox Code Playgroud)

收藏:

win32api.MessageBox(0,"msgbox", "title")
win32api.MessageBox(0,"ok cancel?", "title",1)
win32api.MessageBox(0,"abort retry ignore?", "title",2)
win32api.MessageBox(0,"yes no cancel?", "title",3)
Run Code Online (Sandbox Code Playgroud)