Making shlex.split respect UNC paths

3.9k Views Asked by At

I'm using shlex.split to tokenize arguments for a subprocess.Popen call. However, when one of those args is a UNC path, things get hairy:

import shlex

raw_args = '-path "\\\\server\\folder\\file.txt" -arg SomeValue'
args = shlex.split(raw_args)

print raw_args
print args

produces

-path "\\server\folder\file.txt" -arg SomeValue
['-path', '\\server\\folder\\file.txt', '-arg', 'SomeValue']

As you can see, the backslashes in the front are stripped down. I am working around this by adding the following two lines, but is there a better way?

if args[0].startswith('\\'):
    args[0] = '\\' + args[0]
2

There are 2 best solutions below

0
On BEST ANSWER

I don't know if this helps you:

>>> shlex.split(raw_args, posix=False)
['-path', '"\\\\server\\folder\\file.txt"', '-arg', 'SomeValue']
1
On

Try this:

raw_args = r'-path "\\\\server\\folder\\file.txt" -arg SomeValue'

Note r before the opening single quote.