【问题标题】:Python outputs CR CR LF?Python 输出 CR CR LF?
【发布时间】:2012-07-12 18:19:03
【问题描述】:

我正在编写一个测试脚本,它将简单地运行一个带有几个参数的 *.EXE 文件,然后将结果输出到一个文件中。我有一个 *.sh 测试脚本可以正确运行测试(但需要手动更新以进行更多测试)。此脚本中的行如下所示:

blah.exe arg1 arg2 arg3 > ../test/arg4/arg4.out

我已经编写了一个 python 脚本来根据几个简单的 python 模块自动生成参数(现在很粗糙):

import os
import subprocess

for test_dir in os.listdir():
    if not os.path.isdir(test_dir):
        continue
    # load a few variables from the ./test_dir/test_dir.py module
    test_module = getattr(__import__(test_dir, fromlist=[test_dir]), test_dir)

    # These arguments are relative paths, fix the paths
    arg1 = os.path.join(test_dir, test_module.ARG1)
    arg2 = os.path.join(test_dir, test_module.ARG2)
    arg3 = os.path.join(test_dir, test_module.ARG3)

    proc = subprocess.Popen(["../bin/blah.exe", arg1, arg2, arg3], stdout=subprocess.PIPE)

    stdout_txt = proc.stdout.read().decode("utf-8")

    with open(os.path.join(test_dir, test_dir + '.out'), 'w') as f:
        f.write(stdout_txt)

我已打开文件进行比较,在脚本运行时,我遇到了一个问题。第一个(shell)解决方案输出正确的行尾。第二个(python)解决方案输出以 CR CR LF 结尾的行。这在记事本中看起来是正确的,但在记事本++中,每隔一行似乎都是空白的:

为什么 python 的输出给出了不正确的行结尾?

如何更正行尾?(无需编写其他脚本即可将 CR CR LF 更改为 CR LF)

【问题讨论】:

    标签: python python-3.x mingw eol


    【解决方案1】:

    尝试将universal_newlines=True 参数用于Popen(参见http://docs.python.org/library/subprocess.html#popen-constructor)。

    【讨论】:

    • 哇,这很容易解决,谢谢!我想知道为什么默认情况下没有启用它(经过足够的时间后会接受)。
    • @Darthfett:不是 Python 使用了您所看到的换行符,并且不以任何方式弄乱进程输出的默认行为对我来说似乎是合理的。
    • @Wooble 啊,我不知道这里到底发生了什么。谢谢!如果这是真的,那么由于我继承了 .EXE 的源代码,我想这意味着我可能还有一些工作要做。
    猜你喜欢
    • 2011-03-07
    • 2013-05-25
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2011-01-27
    • 1970-01-01
    相关资源
    最近更新 更多