'Parse Windows command line via Python on Linux
I have a bunch of Windows command line strings like this:
"C:\test\my dir\myapp.exe" -somearg=1 -anotherarg="teststr" -thirdarg
My python scripts work on Ubuntu and need to parse that strings. I need to get the path of the executable file and all arguments in form of dict. What is the easiest way to do that?
I tried to use python`s argparse but can not figure out how to configure it properly (if it is possible at all).
Solution 1:[1]
A very naive implementation of this would be:
STRINGS = [
'"C:\test\my dir\myapp.exe" -somearg=1 -anotherarg="teststr" -thirdarg'
]
def _parse(string):
parsed = {}
string_parts = string.split(' -')
parsed['path'] = string_parts[0]
del string_parts[0]
for arg in string_parts:
kv = arg.split('=')
parsed[kv[0]] = None if len(kv) < 2 else kv[1]
return parsed
def main():
parsed_strings = []
for string in STRINGS:
parsed_strings.append(_parse(string))
print(parsed_strings)
main()
# [{'path': '"C:\test\\my dir\\myapp.exe"', 'somearg': '1', 'anotherarg': '"teststr"', 'thirdarg': None}]
Assuming there are more complex strings with different variations of spaces and dashes, regular expressions might fit better.
Solution 2:[2]
If you know the path is a Windows path, use the PureWindowsPath to gracefully handle Windows paths on Unix:
from pathlib import PureWindowsPath
string = 'C:\test\mydir\myapp.exe somearg'
fn = string.strip().split(" ")[0]
path = PureWindowsPath(fn)
path
> PureWindowsPath('C:\test/mydir/myapp.exe')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | philmaweb |
