Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python subprocess.check_调用-如何将stdout和stderr定向到屏幕和日志文件?_Python_Subprocess - Fatal编程技术网

Python subprocess.check_调用-如何将stdout和stderr定向到屏幕和日志文件?

Python subprocess.check_调用-如何将stdout和stderr定向到屏幕和日志文件?,python,subprocess,Python,Subprocess,我使用Python2.7。这就是我目前从Python启动其他程序所做的,将STDOUT和STERR重定向到日志文件: try: # Execute command and print content to LOGFILE tempname = os.path.abspath('./text.txt') TEMPFILE = open(tempname, 'wb') print 'Executing: ', command

我使用Python2.7。这就是我目前从Python启动其他程序所做的,将STDOUT和STERR重定向到日志文件:

    try:
    # Execute command and print content to LOGFILE
        tempname = os.path.abspath('./text.txt')
        TEMPFILE = open(tempname, 'wb')
        print 'Executing: ', command
        subprocess.check_call(command, shell = True, stdout = TEMPFILE, stderr = TEMPFILE)
        TEMPFILE.close()
        LOGFILE.write(open(tempname, 'rU').read())
        LOGFILE.close()
        os.remove(tempname)
    except Exception as errmsg:
    # If fails then print errors to LOGFILE
        TEMPFILE.close()
        LOGFILE.write(open(tempname, 'rU').read())
        os.remove(tempname)
        print messages.crit_error_bad_command % command, '\n', str(errmsg)
        print >> LOGFILE, messages.crit_error_bad_command % command, '\n', str(errmsg)
        LOGFILE.close() 
首先,我不确定我上面的脚本是不是最好的解决方案。我必须使用临时文件,因为我想捕获日志,即使在subprocess.check_调用失败的情况下也是如此。如果你有如何改进上述脚本的想法,我将不胜感激

此外,我想更改它,以便STDOUT和STDERR可以像平常一样进入屏幕,也可以进入日志文件。我该怎么做?请注意,如果我没有指定STDOUT,我会在屏幕上看到类似“有一个错误,您是否希望继续[y/n]”的内容,然后我可以对此做出反应。现在,由于所有内容都进入日志,我在屏幕上看不到任何内容。我的问题的答案应该有助于解决这个问题

谢谢

我会在屏幕上看到类似“出现错误,是否要继续[y/n]”的内容,然后我可以对此作出反应

要重定向子流程的stdout并手动或使用预定义答案与流程交互,您可以使用:


使用
subprocess.Popen
is实现相同的功能。

如何使用该模块?您可以使用
subprocess Popen.communicate()
,它返回
stdout,stderr
。这样你可以做任何你想做的事情(记录、打印)来进一步添加到@TJD,check_调用是一种方便的方法。对于这种情况来说,它太有限了,这就是为什么您应该使用Popen对象的原因。您能用代码示例详细说明一下吗?我不熟悉Popen。对于Popen,子进程是否会等到进程完全完成后再转到下一个Python命令?如果可能的话,请写一个完整的答案。谢谢。事实上,我通常不希望有互动,因此我的原始方法。但是,有时它发生在我无法控制的情况下,在看不到问题的情况下,程序似乎挂起了,这是不好的。
from contextlib import closing
import pexpect

with open('text.txt', 'rb') as logfile:
    with closing(pexpect.spawn(command, logfile=logfile)) as child:
        # call here child.expect(), child.sendline(), child.interact(), etc