From bfd4130f1f2530201091994790ea8e68cbbd62fc Mon Sep 17 00:00:00 2001 From: Prodesire Date: Mon, 6 Nov 2017 23:41:51 +0800 Subject: [PATCH] add cmd which supply 'sys_argv' method to gain command line from console and its testcase --- pydu/cmd.py | 42 ++++++++++++++++++++++++++++++++++++++++++ tests/test_cmd.py | 8 ++++++++ 2 files changed, 50 insertions(+) create mode 100644 pydu/cmd.py create mode 100644 tests/test_cmd.py diff --git a/pydu/cmd.py b/pydu/cmd.py new file mode 100644 index 0000000..3892166 --- /dev/null +++ b/pydu/cmd.py @@ -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 diff --git a/tests/test_cmd.py b/tests/test_cmd.py new file mode 100644 index 0000000..87aacfc --- /dev/null +++ b/tests/test_cmd.py @@ -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)