【发布时间】:2016-10-10 14:36:45
【问题描述】:
我正在使用subprocess.run() 进行一些自动化测试。主要是为了自动化做:
dummy.exe < file.txt > foo.txt
diff file.txt foo.txt
如果您在 shell 中执行上述重定向,这两个文件总是相同的。但是每当file.txt 太长时,下面的 Python 代码就不会返回正确的结果。
这是 Python 代码:
import subprocess
import sys
def main(argv):
exe_path = r'dummy.exe'
file_path = r'file.txt'
with open(file_path, 'r') as test_file:
stdin = test_file.read().strip()
p = subprocess.run([exe_path], input=stdin, stdout=subprocess.PIPE, universal_newlines=True)
out = p.stdout.strip()
err = p.stderr
if stdin == out:
print('OK')
else:
print('failed: ' + out)
if __name__ == "__main__":
main(sys.argv[1:])
这是dummy.cc中的C++代码:
#include <iostream>
int main()
{
int size, count, a, b;
std::cin >> size;
std::cin >> count;
std::cout << size << " " << count << std::endl;
for (int i = 0; i < count; ++i)
{
std::cin >> a >> b;
std::cout << a << " " << b << std::endl;
}
}
file.txt 可以是这样的:
1 100000
0 417
0 842
0 919
...
第一行的第二个整数是后面的行数,因此file.txt 的长度为 100,001 行。
问题:我是否误用了 subprocess.run() ?
编辑
我在注释后的确切 Python 代码(换行符,rb)被考虑在内:
import subprocess
import sys
import os
def main(argv):
base_dir = os.path.dirname(__file__)
exe_path = os.path.join(base_dir, 'dummy.exe')
file_path = os.path.join(base_dir, 'infile.txt')
out_path = os.path.join(base_dir, 'outfile.txt')
with open(file_path, 'rb') as test_file:
stdin = test_file.read().strip()
p = subprocess.run([exe_path], input=stdin, stdout=subprocess.PIPE)
out = p.stdout.strip()
if stdin == out:
print('OK')
else:
with open(out_path, "wb") as text_file:
text_file.write(out)
if __name__ == "__main__":
main(sys.argv[1:])
这是第一个差异:
这里是输入文件:https://drive.google.com/open?id=0B--mU_EsNUGTR3VKaktvQVNtLTQ
【问题讨论】:
-
您可能没有正确刷新缓冲区。
-
你是什么意思?我该如何冲洗它?
-
@user2346536 如果是冲洗问题,您可以使用
sys.stdout.flush()(不确定是否存在)。这个文件有多长? -
10000 行太长了。测试冲洗...
-
刷新不起作用。选择的答案解释了为什么,因为无论如何,我在刷新之前都在内存中。但是不错的尝试,无论如何+1 :)
标签: python c++ python-3.x subprocess io-redirection