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).
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.
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.