Windows上的Python:path as subprocess参数被修改并生成

2024-10-01 17:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows和Python 2.6上使用子进程,如下所示。我正在尝试使用遗留解析器应用程序(assume parser.py)解析文本文件,如下所示:

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

这里的问题是文件名传递给遗留应用程序的方式,在遗留应用程序中,我不能更改代码,但只能使用Python访问它。

它生成时出现以下错误:

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

当我从回溯中复制修改后的文件名(带有双正斜杠)以检查是否存在时,系统无法找到它。

问题:如何将路径作为参数传递,以便在不更改为双斜杠的情况下对其进行处理,以便系统可以读取文件?

注意:os.sep也不能解决这个问题。

编辑:使用os.system执行可以很好地工作,但存在的问题是获取输出供以后使用。Am当前在一个模块(run_parser.py)中使用os.system,然后在另一个模块(get_parse_status.py)中使用子进程,该模块弹出run_parser.py以获取输出。如果有什么比这更好的,我会很感激的。

谢谢你的时间。


Tags: 模块runpytxt应用程序parser进程os
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)

"C:\Report1\2011-03-14.txt" isn't the same as the path C:\Report1\2011-03-14.txt. It's actually some bytestring, 'C:\Report1\x811-03-14.txt'. Strangely enough it doesn't sound like this is your issue, but it might be related. r"C:\Report1\2011-03-14.txt" fixes this.

But be aware that double backslashes in the printed representation doesn't necessarily mean that there are actually two backslashes. '\' is a Python string of length 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()

我发现,在通过Popen在命令行上传递参数时,将参数括在双引号中是使其正常工作的唯一可靠方法。我也不总是信任调用Popen的list方法,通常我自己形成命令。还要注意原始指示器(r'')。

"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"解决了这个问题。

但是请注意,打印表示中的双反斜杠并不一定意味着实际上有两个反斜杠。'\\'是长度为1的Python字符串。

相关问题 更多 >

    热门问题