我想在终端中用python创建一个进度条.首先,我必须得到终端窗口的宽度(列).在python 2.7中,没有标准库可以在Windows上执行此操作.我知道也许我必须手动调用Windows Console API.
根据MSDN和Python文档,我编写了以下代码:
import ctypes
import ctypes.wintypes
class CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
_fields_ = [
('dwSize', ctypes.wintypes._COORD),
('dwCursorPosition', ctypes.wintypes._COORD),
('wAttributes', ctypes.c_ushort),
('srWindow', ctypes.wintypes._SMALL_RECT),
('dwMaximumWindowSize', ctypes.wintypes._COORD)
]
hstd = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-11)) # STD_OUTPUT_HANDLE = -11
print hstd
csbi = CONSOLE_SCREEN_BUFFER_INFO()
print ctypes.sizeof(csbi) # <---------------
ret = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(ctypes.c_ulong(hstd), csbi)
print ret
print csbi.dwSize.X
Run Code Online (Sandbox Code Playgroud)
它工作正常.我开始print在代码中删除一些.但在那之后,它不起作用!GetLastError返回6(无效句柄).经过多次尝试,我发现在代码的指向位置必须有一些东西,例如print 'hello',import sys或sys.stdout.flush().起初,我想也许需要时间做点什么.所以我试着把它放在time.sleep(2)那个位置,但它仍然不起作用.
但是,如果我使用struct而不是ctypes.Structure,则没有这样的问题.
import ctypes
import struct
hstd = ctypes.windll.kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE = -11 …Run Code Online (Sandbox Code Playgroud)