簡體   English   中英

Python子進程:為什么stdin = PIPE會更改某些命令的輸出?

[英]Python subprocess: Why does stdin=PIPE change the output of some commands?

如果使用stdin進行管道傳輸,則某些交互式命令的輸出將有所不同。 這是為什么?

下面我測試subprocess.Popen在3個不同的命令上打開和關閉stdin。


碼:

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的內容發生變化?

是的,如果您正在管道或重定向輸入,則某些程序的行為會有所不同。 您可以像這樣檢測到它:

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

這在* nix以及Windows上均可使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM