在写stdin之前从os.popen4读取输出

时间:2012-07-20 15:07:30

标签: python

我有一个使用os.popen4执行某些命令的脚本。问题是执行某些时间命令将需要用户输入(“y”或“n”)。我正在阅读stdout / stderr并打印它,但似乎来自命令的问题没有被打印并且它挂起。为了使它工作,我不得不盲目地向stdin写“n”。有人可以指导如何处理它吗?

代码无效:

   (f_p_stdin, f_p_stdout_stderr) = os.popen4(cmd_exec,"t")
    cmd_out = f_p_stdout_stderr.readlines()
    print cmd_out
    f_p_stdin.write("n")
    f_p_stdin.close()
    f_p_stdout_stderr.close()

工作代码:

   (f_p_stdin, f_p_stdout_stderr) = os.popen4(cmd_exec,"t")
    cmd_out = f_p_stdout_stderr.readlines()
    f_p_stdin.write("n")
    f_p_stdin.close()
    print cmd_out
    f_p_stdout_stderr.close()

注意:我知道它已被折旧并且使用了子进程模块,但是现在我不知道如何使用它。所以如果有人帮我用os.popen4来处理它,我将不胜感激。我想捕获问题并处理用户的输入并执行它。

1 个答案:

答案 0 :(得分:0)

readlines():返回包含文件中所有数据行的列表。如果从这种情况下的过程中读取,则很可能不会发送换行符和/或刷新输出。您应该从输入中读取字符并处理该字符以查看是否提出了问题。

了解cmd_exec的外观会有所帮助,以便其他人可以尝试并模仿您的尝试。


更新

我在Python中编写了一个uncheckout命令:

#! /usr/bin/env python
# coding: utf-8

import sys

print 'Uncheckout of {} is irreversible'.format(sys.argv[1])
print 'Do you want to proceed? [y/N]',
sys.stdout.flush()
x = raw_input()

if x == 'y':
    print sys.argv[1], "no longer checked out"
else:
    print sys.argv[1], "still checked out"

我故意将提示字符串作为raw_input的参数,以便能够明确地执行flush()

您的代码片段都不适用(假设cmd_exec['./uncheckout', 'abc.txt']'./uncheckout abc.txt'popen4()在后​​一种情况下使用shell来启动程序)。 只有当我将readlines()移动到write()和close()之后,命令才会继续。 这对我来说很有意义,因为close()会刷新输出。您正在以文本模式编写,并且正常缓冲直到行结束,这不在您的.write('n')中。

为了能够检查提示的内容并对其进行测试和反应。以下内容适用于上述uncheckout

#! /usr/bin/env python
# coding: utf-8

import os
import sys

cmd_exec = ['./uncheckout', 'abc.txt']

(f_p_stdin, f_p_stdout_stderr) = os.popen4(cmd_exec,"t")
line = ''
while True:
    x = f_p_stdout_stderr.read(1)
    if not x:
        break
    sys.stdout.write(x)
    sys.stdout.flush()
    if x == '\n':
        line = ''
    else:
        line += x
    if line.endswith('[y/N]'):
        f_p_stdin.write("n\n")
        f_p_stdin.flush()
        sys.stdout.write('\n')

也许你可以从那里向后工作,制作适合你的东西。确保在适当的地方保持冲洗。

相关问题