1

我正在使用 python 脚本来执行基于 Ant 的框架批处理文件(Helium.bat)

subprocess.Popen('hlm '+commands, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

但是,脚本在执行 .bat 文件时将始终停止并显示以下错误:

import codecs
  File "C:\Python25\lib\codecs.py", line 1007, in <module>
    strict_errors = lookup_error("strict")
  File "C:\Python25\lib\codecs.py", line 1007, in <module>
    strict_errors = lookup_error("strict")
  File "C:\Python25\lib\encodings\__init__.py", line 31, in <module>
    import codecs, types
  File "C:\Python25\lib\types.py", line 36, in <module>
    BufferType = buffer
NameError: name 'buffer' is not defined

如果我直接在命令行上执行 .bat ,不会有任何问题。

4

1 回答 1

1

我认为至少部分问题在于您如何执行批处理文件。试试这个:

# execute the batch file as a separate process and echo its output
Popen_kwargs = { 'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT,
                 'universal_newlines': True }
with subprocess.Popen('hlm '+commands, **Popen_kwargs).stdout as output:
    for line in output:
        print line,

这将不同的参数传递给Popen- 不同之处在于此版本删除shell=True了批处理文件中不需要的参数,设置stderr=subprocess.STDOUT重定向stdout到 stdout 将要避免丢失任何错误消息的同一位置,并添加 auniversal_newlines=True以使输出更多可读。

另一个区别是它读取并打印Popen进程的输出,这将有效地使运行批处理文件的 Python 脚本等到它完成执行后再继续 - 我怀疑这很重要。

于 2010-12-13T10:53:31.517 回答