【问题标题】:stdin.write() being blocked from interacting with foil.exestdin.write() 被阻止与 foil.exe 交互
【发布时间】:2015-09-09 13:29:06
【问题描述】:

我正在为 Xfoil 编写一个包装器,我的第一个命令集是:

commands=[]

commands.append('plop\n')
commands.append('g,f\n')
commands.append('\n')
commands.append('load '+ afile+'\n')
commands.append('\n')
#commands.append('ppar\n');
#commands.append('n %g\n',n);
commands.append('\n')
commands.append('\n')
commands.append('oper\n')
commands.append('iter '+ str(iter) + '\n')
commands.append('visc {0:f}\n'.format(Re))
commands.append('m {0:f}\n'.format(M))

我正在与 xfoil 进行如下交互:

xfoil_path=os.getcwd()+'/xfoil.exe'
Xfoil = Popen(xfoil_path, shell=True, stdin=PIPE, stdout=None, stderr=None, creationflags=0)
for i in commands:
    print '\nExecuting:', i
    #stdin.write returns None if write is blocked and that seems to be the case here
    Xfoil.stdin.write(i)
    Xfoil.wait()
    #print Xfoil.stdin.write(i)

但是,Xfoil.stdin.write 被阻止与程序交互 - xfoil.exe - 因为 Xfoil.stdin.write(i) 返回 None。

这发生在第一个命令之后,即 plop

我该如何解决这个问题?

【问题讨论】:

  • 写完first command 项后,您正在等待程序结束。你确定那不是问题的根源吗? BTW shell=True 在这里是不必要的。路径应与os.path.join() 结合使用。 commands 与所有这些 append() 调用的构建看起来很奇怪。为什么不只创建一个包含这些内容的列表,而不是创建一个空列表并执行所有这些append()s。 i 对于不是整数的东西来说是个坏名字,尤其是作为循环变量。

标签: python stdin popen


【解决方案1】:

解决方法是添加 Xfoil.stdin.close();关闭缓冲区允许程序继续。

Xfoil = Popen(xfoil_path, shell=True, stdin=PIPE, stdout=None, stderr=None, creationflags=0)
for i in commands:
    Xfoil.stdin.write(i)

Xfoil.stdin.close()
Xfoil.wait()

寻求帮助了解为什么需要添加 Xfoil.stdin.close()。关闭缓冲区如何允许 xfoil.exe 继续?

【讨论】:

  • 因为只有flush()close() 文件才能确保缓冲数据实际写入该管道。
  • @BlackJack: bufsize=0 在 Python 2 上;你在这里不需要flush()
【解决方案2】:

要发送多个命令,您可以use Popen.communicate() method 发送命令,关闭管道并等待子进程完成:

import os
from subprocess import Popen, PIPE

process = Popen(os.path.abspath('xfoil.exe'), stdin=PIPE)
process.communicate(b"".join(commands))

Xfoil.wait() 在您的代码中等待可执行文件在第一个命令之后完成。关闭管道 (Xfoil.stdin) 表示 EOF,否则如果 xfoil.exe 读取到 EOF 可能会发生死锁(否则没有命令使其退出)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2013-01-11
    • 2017-11-02
    • 1970-01-01
    • 2014-04-27
    相关资源
    最近更新 更多