【问题标题】:Python subprocess: Why does stdin=PIPE change the output of some commands?Python 子进程:为什么 stdin=PIPE 会改变某些命令的输出?
【发布时间】:2013-02-09 21:58:00
【问题描述】:

如果标准输入是管道,一些交互命令的输出会有所不同。这是为什么呢?

下面我在 3 个不同的命令上测试 subprocess.Popen,有和没有标准输入管道。

 
代码:

import subprocess, time


def run_command(command, enable_input):
    print 'command="{}", enable_input={}:'.format(command, enable_input)

    # Launch the process and set up pipes.
    if enable_input:
        stdin = subprocess.PIPE
    else:
        stdin = None
    child = subprocess.Popen(command, stdin=stdin)

    # Wait a second for output.
    time.sleep(1)

    # Terminate the child if it hasn't finished.
    if child.poll() == None:
        child.terminate()

    print '\n-----' # Print a separator


commands = ('cmd', 'python', 'timeout 1')
for command in commands:
    run_command(command, enable_input=False)
    run_command(command, enable_input=True)

 
输出:

command="cmd", enable_input=False:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\>
-----
command="cmd", enable_input=True:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\>
-----
command="python", enable_input=False:
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
-----
command="python", enable_input=True:

-----
command="timeout 1", enable_input=False:

Waiting for 0 seconds, press a key to continue ...

-----
command="timeout 1", enable_input=True:
ERROR: Input redirection is not supported, exiting the process immediately.

-----

 
下面链接的问题的答案表明,某些程序试图检测它们是由人还是由脚本运行。这里是这样吗?如果是这样,他们如何在 Windows 上检测到这一点?

Why does supplying stdin to subprocess.Popen cause what is written to stdout to change?

【问题讨论】:

    标签: python windows subprocess pipe stdin


    【解决方案1】:

    是的,如果您使用管道或重定向输入,某些程序的行为会有所不同。你可以像这样检测它:

    import sys
    print sys.stdin.isattty()   # True if it's a terminal, False if it's redirected
    

    这适用于 *nix 以及 Windows。

    【讨论】:

    • 谢谢!在那种情况下,我还有一个问题:有没有办法伪装成终端(在 Windows 中)?
    • 这不是一个很好的解决方案,但串行端口可能被视为终端(取决于上下文),所以如果你足够绝望,你可以尝试使用空调制解调器模拟器,如 com0com 或衍生产品
    • 我计划分发我的程序,所以我认为这会增加太多内容。但这是一个有趣的想法。
    猜你喜欢
    • 2020-08-06
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    相关资源
    最近更新 更多