Разбор командной строки в PythonPython

Программы на Python
Anonymous
Разбор командной строки в Python

Сообщение Anonymous »

Я пытаюсь проанализировать командную строку Windows на исполняемый файл (например, «python.exe»), файл сценария/EXE-файл, который запускает команда, и аргументы, передаваемые в этот файл.
Вот что я сделал на данный момент:
def parse_cmd(cmd):
executable = filepath = args = ""
split_cmd = shlex.split(cmd, posix=False)

# Find files in command line, without including python.exe
files = [s for s in split_cmd if s.strip('"').endswith((".py", ".bat", ".exe")) and s not in sys.executable]

if files:
filepath = files[0]
i = split_cmd.index(filepath)
executable_list = split_cmd[:i] # Get the elements before the file
args_list = split_cmd[i + 1:] # Get the elements after the file

filepath = filepath.strip('"')
executable = " ".join(executable_list)
args = " ".join(args_list)

return executable, filepath, args

Есть ли лучшие способы реализовать это?
Примеры вызова этого метода:
cmd1 = "python.exe foo.py --arg1 foo --arg2 bar"
res1 = parse_cmd(cmd1)
print(res1)
cmd2 = 'test.exe -arg1 "foo"'
res2 = parse_cmd(cmd2)
print(res2)
cmd3 = "echo test"
res3 = parse_cmd(cmd3)
print(res3)
cmd4 = r'py -3 -E "test new\test.py"'
res4 = parse_cmd(cmd4)
print(res4)

Выход:
('python.exe', 'foo.py', '--arg1 foo --arg2 bar')
('', 'test.exe', '-arg1 "foo"')
('', '', '')
('py -3 -E', 'test new\\test.py', '')


Подробнее здесь: https://stackoverflow.com/questions/782 ... -in-python

Вернуться в «Python»