add cmd which supply 'sys_argv' method to gain command line from console and its testcase

This commit is contained in:
Prodesire 2017-11-06 23:41:51 +08:00
parent e62a5990f1
commit bfd4130f1f
2 changed files with 50 additions and 0 deletions

42
pydu/cmd.py Normal file
View File

@ -0,0 +1,42 @@
import sys
from pydu import WINDOWS
from pydu.compat import PY2
if PY2 and WINDOWS:
# https://bitbucket.org/techtonik/python-wget
def sys_argv():
"""
Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
strings.
Versions 2.x of Python don't support Unicode in sys.argv on Windows,
with the underlying Windows API instead replacing multi-byte characters
with '?'.
"""
from ctypes import POINTER, byref, cdll, c_int, windll
from ctypes.wintypes import LPCWSTR, LPWSTR
GetCommandLineW = cdll.kernel32.GetCommandLineW
GetCommandLineW.argtypes = []
GetCommandLineW.restype = LPCWSTR
CommandLineToArgvW = windll.shell32.CommandLineToArgvW
CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
CommandLineToArgvW.restype = POINTER(LPWSTR)
cmd = GetCommandLineW()
argc = c_int(0)
raw_argv = CommandLineToArgvW(cmd, byref(argc))
argnum = argc.value
sysnum = len(sys.argv)
argv = []
if argnum > 0:
# Remove Python executable and commands if present
start = argnum - sysnum
for i in range(start, argnum):
argv.append(raw_argv[i])
return argv
else:
def sys_argv():
return sys.argv

8
tests/test_cmd.py Normal file
View File

@ -0,0 +1,8 @@
from pydu.compat import text_type
from pydu.cmd import sys_argv
def test_sys_argv():
argv = sys_argv()
for s in argv[1:]:
assert isinstance(s, text_type)