subprocess.Popen - 再次重定向标准输入
subprocess.Popen - redirect stdin again
假设有一个名为 'ABC' 的程序,它从标准输入读取 4 个整数并用它们做一些事情。
最近,我了解到我们可以使用管道将输入提供给 ABC,如下所示:
# send.py
import subprocess
p = subprocess.Popen(['ABC'], stdin = subprocess.PIPE)
print >>p.stdin, '1 2 3 4'
我的问题是:我们可以在调用 subprocess.Popen
后再次重定向标准输入吗?例如,
# send.py
import subprocess
p = subprocess.Popen(['ABC'], stdin = subprocess.PIPE)
print >>p.stdin, '1 2 3'
(Redirect p.stdin to terminal's stdin)
,这样我们就可以在终端上输入第 4 个整数到 ABC。
重定向发生在 ABC
执行之前,例如(在 Unix 上)在 fork()
之后但在 execv()
之前(look at dup2()
calls)。在 Popen()
returns 之后使用相同的 OS 级别机制进行重定向为时已晚,但您可以手动模拟它。
到"redirect p.stdin
to terminal's stdin"当进程运行时,调用shutil.copyfileobj(sys.stdin, p.stdin)
。可能存在缓冲问题,子进程可能会在其标准输入之外读取,例如,直接从 tty。参见 Q: Why not just use a pipe (popen())?
您可能想要 pexpect
's .interact()
(未测试):
#!/usr/bin/env python
import pexpect # $ pip install pexpect
child = pexpect.spawnu('ABC')
child.sendline('1 2 3')
child.interact(escape_character=None) # give control of the child to the user
您可以先要求第四个整数,然后将其与其他 3 个一起发送:
p = subprocess.Popen(['ABC'], stdin=subprocess.PIPE)
fourth_int = raw_input('Enter the 4th integer: ')
all_ints = '1 2 3 ' + fourth_int
p.communicate(input=all_ints)
假设有一个名为 'ABC' 的程序,它从标准输入读取 4 个整数并用它们做一些事情。
最近,我了解到我们可以使用管道将输入提供给 ABC,如下所示:
# send.py
import subprocess
p = subprocess.Popen(['ABC'], stdin = subprocess.PIPE)
print >>p.stdin, '1 2 3 4'
我的问题是:我们可以在调用 subprocess.Popen
后再次重定向标准输入吗?例如,
# send.py
import subprocess
p = subprocess.Popen(['ABC'], stdin = subprocess.PIPE)
print >>p.stdin, '1 2 3'
(Redirect p.stdin to terminal's stdin)
,这样我们就可以在终端上输入第 4 个整数到 ABC。
重定向发生在 ABC
执行之前,例如(在 Unix 上)在 fork()
之后但在 execv()
之前(look at dup2()
calls)。在 Popen()
returns 之后使用相同的 OS 级别机制进行重定向为时已晚,但您可以手动模拟它。
到"redirect p.stdin
to terminal's stdin"当进程运行时,调用shutil.copyfileobj(sys.stdin, p.stdin)
。可能存在缓冲问题,子进程可能会在其标准输入之外读取,例如,直接从 tty。参见 Q: Why not just use a pipe (popen())?
您可能想要 pexpect
's .interact()
(未测试):
#!/usr/bin/env python
import pexpect # $ pip install pexpect
child = pexpect.spawnu('ABC')
child.sendline('1 2 3')
child.interact(escape_character=None) # give control of the child to the user
您可以先要求第四个整数,然后将其与其他 3 个一起发送:
p = subprocess.Popen(['ABC'], stdin=subprocess.PIPE)
fourth_int = raw_input('Enter the 4th integer: ')
all_ints = '1 2 3 ' + fourth_int
p.communicate(input=all_ints)