8

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]
Adam Lear
  • 38,111
  • 12
  • 81
  • 101
  • Your question is uncertain. In the example above you are using string literals. You can cope with them by using the technique in dusan's answer or simply by using raw string literals. However, you commented on my answer that the strings are taken from a file. In this case, Python will not even try to touch them, they will have the same amount of slashes. Try loading your string from a file and printing it. Either that, or I'm missing something obvious. – Alexei Sholik Jan 31 '11 at 10:22
  • @Alex Good point. I'd reproduced the behaviour I saw when loading the string from a file in the sample above, so I assumed it'd behave similarly. I'll double-check what the string looks like if loaded from the file. – Adam Lear Jan 31 '11 at 13:55

2 Answers2

15

I don't know if this helps you:

>>> shlex.split(raw_args, posix=False)
['-path', '"\\\\server\\folder\\file.txt"', '-arg', 'SomeValue']
dusan
  • 9,104
  • 3
  • 35
  • 55
0

Try this:

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

Note r before the opening single quote.

Alexei Sholik
  • 7,287
  • 2
  • 31
  • 41