Python 子进程允许用户交互

标签 python fortran subprocess

我正在尝试从 python 脚本运行一些学生 FORTRAN 程序。这些程序没有按任何特定顺序编写,并且通常依赖于简单的 FORTRAN read(*,*) 命令。一个简单的程序可以是:

program main
    implicit none
    real :: p,t
    write(*,*)'Enter p'
    read(*,*)p
    write(*,*)'Enter t'
    read(*,*)t
    write(*,*)p,t
end program main

此代码暂停并允许用户根据提示输入某些信息。我希望通过使用 subprocess Popen 命令来实现类似的功能。脚本在运行之前不会知道输入是什么,或者是否需要发生。

目前,对于无需输入的程序,以下脚本有效:

p = sub.Popen('./file',stdout=sub.PIPE,stderr=sub.PIPE,stdin=sub.PIPE,shell=True)
output,error = p.communicate()

有什么方法可以让脚本运行程序在程序运行时在终端中输入数据吗?

最佳答案

您似乎想使用 pexpect :

import pexpect
child = pexpect.spawn('student_program')
while child.expect('Enter (\w+)\r\n', pexpect.EOF) == 0:
    if child.match[1] == 'p':
        child.sendline('3.14159')

要将程序的交互式控制传递给用户,请使用child.interact()

关于Python 子进程允许用户交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11635909/

相关文章:

printing - 如何在Fortran中合并两个字符串

python - 从 ffmpeg 获取实时输出以在进度条中使用(PyQt4,stdout)

Python - UDP 客户端

Python argparse 选项子解析器

python - 如何在多索引 Pandas 数据框中获取随机样本?

fortran - 澄清一个 fortran 隐含循环

python - pdb 中的 'n' 使我进入 pdb.set_trace() 方法

fortran - Gfortran编译错误: Logicals at (1) must be compared with . eqv。而不是 ==

python - 为什么十六进制数字在 python 子进程中没有正确传递

python - subprocess 中的 'shell' 参数在 Windows 上意味着什么?