0

stdin がパイプ処理されている場合、一部の対話型コマンドの出力は異なります。何故ですか?

以下では、標準入力パイプの有無にかかわらず、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 でそれをどのように検出しますか?

stdin を subprocess.Popen に指定すると、stdout に書き込まれる内容が変更されるのはなぜですか?

4

1 に答える 1

3

はい、入力をパイプまたはリダイレクトしている場合、一部のプログラムは異なる動作をします。次のように検出できます。

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

これは、Windowsだけでなく*nixでも機能します。

于 2013-02-24T19:08:33.553 に答える