Python on Windows: path as an argument of a subprocess changes and generates an error

We use the subprocess on Windows and Python 2.6 as follows. I am trying to parse a text file using an outdated parser application (suppose parser.py) as follows:

import subprocess
k = subprocess.Popen(['python', 'parser.py', '-f C:\Report1\2011-03-14.txt'],
                     shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print k.communicate()

The problem here is how the file name is passed to the legacy application, where I cannot change the code, but I can only access it using Python.

It is generated with the following error:

IOError: [Errno 22] invalid mode (\'r\') or filename: C:\\Report1\\2011-03-14.txt

When I copy the changed file name (double slash) from traceback to check for existence, the system cannot find it.

Question . How to pass a path as an argument, so that it is processed without conversion to double slashes, so that the system can read the file?

NOTE. os.sep also does not resolve the problem.

EDIT: os.system , , . os.sytem (run_parser.py), (get_parse_status.py), Popens run_parser.py, . , .

.

+3
3

, :

k = subprocess.Popen(['python', 'parser.py', '-f', r'C:\Report1\2011-03-14.txt'],
                     shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

, :

import sys
import os
userinput = sys.argv[1]
data = open(userinput, 'rb').read()
datalength = len(data)
fname = os.path.basename(userinput)
print "%s datasize = %s" % (fname, datalength)

, :

>>> k = subprocess.Popen(['python', 'test2.py', 'w:\bin\test2.py'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> k.communicate()
5: ('Traceback (most recent call last):\r\n  File "w:\\bin\\test2.py", line 4, in <module>
data = open(userinput, \'rb\').read()
IOError: [Errno 22] invalid mode (\'rb\') or filename: 'w:\\x08in\\test2.py', None)
>>> k = subprocess.Popen(['python', r'w:\bin\test2.py', r'w:\bin\test2.py'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> k.communicate()
6: ('test2.py datasize = 194\n', None)
+3

"C:\Report1\2011-03-14.txt" C:\Report1\2011-03-14.txt. , 'C:\\Report1\x811-03-14.txt'. , , , . r"C:\Report1\2011-03-14.txt" .

, , . '\\' - Python 1.

+3

"C:\Report1\2011-03-14.txt" - , C:\Report1\2011-03-14.txt. bytestring, 'C:\Report1\x811-03-14.txt'. , , , . r "C:\Report1\2011-03-14.txt" .

, , . '\' - Python 1.

:

from subprocess import Popen, PIPE
k = Popen(r'python parser.py -f "C:\Report1\2011-03-14.txt"',
          shell=True, 
          stdout=PIPE, 
          stderr=STDOUT)
print k.communicate()

I find that often when passing args on the command line through Popen, including parameters in double quotes is the only reliable way to make it behave. I also do not always trust Popen's call list method and usually form the command myself. Also note the raw indicator (r``).

+1
source

All Articles