我正在使用 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,不会有任何问题。
最佳答案
我认为至少部分问题在于您如何执行批处理文件。尝试一下:
# 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 将避免丢失任何错误消息的同一位置,并添加 universal_newlines=True
以使输出更具可读性。
另一个区别是它读取并打印 Popen
进程的输出,这将有效地使运行批处理文件的 Python 脚本等到它完成执行后再继续 - 我怀疑这很重要。
关于python - 名称错误 : name 'buffer' is not defined with Ant Based framework batch file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4427494/