【发布时间】:2013-05-12 13:28:55
【问题描述】:
我有两个程序。第一个 (subprocess.cpp) 用 C++ 编写:
#include <stdio.h>
int main() {
char * line = new char[1000];
// first scan
scanf("%s\n", line);
printf("%s\n", line);
fflush(stdout);
// second scan
scanf("%s\n", line);
printf("%s\n", line);
fflush(stdout);
return 0;
}
这个程序只是从标准输入中获取两个字符串并在标准输出上打印,毕竟是刷新。
这是用 Python 2.7 编写的第二个程序 (test.py):
from subprocess import Popen
from subprocess import PIPE
from subprocess import Popen
# create process
my_process = Popen("./subprocess", stdin = PIPE, stdout = PIPE)
# send initial data
my_process.stdin.write('abc\n')
my_process.stdin.flush()
my_process.stdin.write('xyz\n')
my_process.stdin.flush()
# read data from subprocess
print "Subprocess line 1 :: " + str(my_process.stdout.readline())
print "Subprocess line 2 :: " + str(my_process.stdout.readline())
这个脚本应该启动子进程,发送和检索两个字符串。看看发生了什么:
marcin@marcin-Aspire-7540 ~/Desktop/inzynierka $ g++ subprocess.cpp -o subprocess
marcin@marcin-Aspire-7540 ~/Desktop/inzynierka $ python test.py
Subprocess line 1 :: abc
test.py 正在等待程序 subprocess 的第二行。程序 subprocess 无法发送第二个字符串,因为它正在等待 '\n' 字符。
如果我将subprocess.cpp 中的第二个scanf 更改为scanf("%s\n", line);(没有\n),一切正常。当我在test.py 中再发送一行时也会发生同样的情况:
# send initial data
my_process.stdin.write('abc\n')
my_process.stdin.flush()
my_process.stdin.write('xyz\n')
my_process.stdin.flush()
my_process.stdin.write('ADDITIONAL\n')
my_process.stdin.flush()
似乎 Python 不会在刷新后发送最后一个 \n 字符(参见更改 scanf 的示例)。在test.py 中添加一个额外的写入和刷新证明,在刷新后丢失的 \n 字符仍在缓冲区中。
怎么办?如何让 Python 的 flush 刷新所有字符?
【问题讨论】: