4

main.py

import subprocess,sys
process = subprocess.Popen([sys.executable]+['example.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while True:
    out = process.stdout.read(1)
    if not out:
        out=process.stderr.read(1)
    if out == '' and process.poll() != None:
        break
    if out != '':
        print out

example.py

f=raw_input('WHats your favorite animal')

わかりました。メインループで入力を確認し、それにデータを提供するにはどうすればよいのでしょうか。現在、raw_inputを使用すると、プログラムがフリーズします。

これが私が欲しいものです

while True:
    out = process.stdout.read(1)
    if not out:
        out=process.stderr.read(1)
    if out == '' and process.poll() != None:
        break
    #showing what i want
    if request_input==True:
        give_input('cat') #Give input to the raw_input
    #
    if out != '':
        print out

このような機能があるかどうかはわかりません。さらに説明が必要な場合はコメントしてください。

4

4 に答える 4

4

これは、プロセス間通信を行うための最良の方法ではありません。通信と同期のために、マルチプロセッシングまたはスレッド ライブラリを Queue や PIPE などと一緒に使用することをお勧めします。

キューはデータを共有するための最も簡単な方法であり、あるプロセスが値を入力し、別のプロセスが値を取得します。

元のコードを修正したので、今は動作します。raw_input がハングするものがない場合、stdout をそのままフラッシュしないことに注意してください。http : //code.activestate.com/lists/python-list/265749/なぜあなたのコードは標準出力を待っていたのですか...

これは危険です。デッドロックが発生する可能性があります。自己責任で使用し、別の方法を試してください。

import sys
print 'Whats your favorite animal\n' #raw_input doesn't flush :( and we want to read in a whole line
sys.stdout.flush()
f = raw_input()
print f

および対応する main.py

import subprocess, sys, os
process = subprocess.Popen([sys.executable]+['example.py'],
     stdout = subprocess.PIPE, stderr = subprocess.PIPE, stdin = subprocess.PIPE)

while True:
    if process.poll() != None:
        break
    request_input = process.stdout.readline() # read line, this will wait until there's actually a line to read.
    if request_input == "Whats your favorite animal\n":
        print 'request: %s sending: %s' % (request_input, 'cat')
        process.stdin.write('cat\n')
       process.stdin.flush()
于 2012-06-12T23:20:50.267 に答える
1

編集: あなたの質問を誤解しているようです、申し訳ありません。

これはあなたが思うほど簡単ではありません:

selectに利用可能なデータがあるかどうかを確認するために使用する必要があります。データstdinがある場合は、それを読み取ります。

最小限の例:

STDIN, STDOUT = 0, 1

while not process.poll() is None:
    out = process.stdout.read(1)

    if not out:
        break

    try:
        fds = select.select([STDIN], [], [])[0]
    except select.error:
        pass
    else:
        if STDIN in fds:
            data = os.read(STDIN, 1024)

            if data_requested:
                process.stdin.write(data)

選択する情報: http://docs.python.org/library/select.html#module-selecthttp://linux.die.net/man/2/selectおよびhttp://en.wikipedia.org/ wiki/Select_(Unix)

selectWindowsはソケットのみをサポートするため、これが Windows で機能するかどうかは不明です。SO に関する質問: Windows で epoll/kqueue/select に相当するものはどれですか?

于 2012-06-16T14:42:57.243 に答える
0

マルチプロセッシングモジュールを使用してみてください

from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print num.value
    print arr[:]
于 2012-06-20T21:08:36.110 に答える
0

「生のPython」を主張しない限り、pexpectモジュールを使用するのが最善です。example.pyに出力を追加しました。それ以外の場合は、まったく面白くありません。

これがexample.pyです:

    f=raw_input('WHats your favorite animal')
    print f.upper()

これがあなたが探しているpexpect-example.pyです:

    # see http://pexpect.sourceforge.net/pexpect.html
    import pexpect

    PY_SCRIPT = 'example.py'

    child = pexpect.spawn('python %s' % PY_SCRIPT)

    child.expect ('WHats your favorite animal')

    # comment out these three lines if you run unmodified example.py script
    child.setecho(False)
    child.sendline ('cat')
    print PY_SCRIPT, 'said:', child.readline()
于 2012-06-22T16:09:41.873 に答える