0

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).

Victor Mezrin
  • 2,797
  • 2
  • 32
  • 48
  • Please post how you'd like the dictionary to look. – nir0s Mar 10 '17 at 18:12
  • What was the problem with `argparse`? I think it is the correct tool for this job. Using it along with `vars` can give you a dictionary: http://stackoverflow.com/a/16878364/3901060 – FamousJameous Mar 10 '17 at 20:36

2 Answers2

0

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.

nir0s
  • 1,151
  • 7
  • 17
0

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')
philmaweb
  • 514
  • 7
  • 13