1

エミュレートされたユーザーデータを使用していくつかのシェルコマンドを実行するプログラムを作成しようとしています。

問題は、コードの最後に次の行がないと、シェルコマンドが正しく実行されないことです。

raw_input('press <enter> to exit')

どうすればその行を取り除くことができますか?

child = pexpect.spawn('grunt init:gruntfile')
child.logfile_read = sys.stdout

child.expect ('Is the DOM involved in ANY way?')
child.sendline ('y')
child.logfile_read = sys.stdout

child.expect ('Will files be concatenated or minified?')
child.sendline ('y')
child.logfile_read = sys.stdout

child.expect ('Will you have a package.json file?')
child.sendline ('y')
child.logfile_read = sys.stdout

child.expect ('Do you need to make any changes to the above before continuing?')
child.sendline ('n')
child.logfile_read = sys.stdout

raw_input('press <enter> to exit')
4

2 に答える 2

6

問題は、プログラムを遅くする raw_input がないと、子プロセスが終了する前に Python スクリプトが終了する (そしてプロセス内の子プロセスを強制終了する) ことです。

この状況を処理することになっていると思いますが、子プロセスの終了後に未読の出力がある場合、wait() がハングするようにドキュメントpexpect.wait()から聞こえます。子プロセスの詳細を知らなければ、そこにあるかどうかはわかりません発生するリスクです。read() と wait() のいくつかの組み合わせが機能する可能性があります。または、それを理解するのが面倒な場合は、time.sleep() を数秒だけ実行できます。

于 2012-04-30T08:13:09.683 に答える
0

この質問が出されてからしばらく経っていることは承知していますが、この質問に出くわし、自分に合ったものを志願しようと思いました.

私は基本的に、プロセスが完了したかどうかを尋ねる while ループをセットアップし、完了しなかった場合はエラーをスローしました。そうすれば、自動化をそれほど悪くしなくても、私にとってより意味のある方法でエラーが発生する、より柔軟な待機ができます。

これは、プログラムが終了する前に、一連の対話型プロンプトの最後で何かが実行されるのを待つためのものであることも指摘しておく必要があります。したがって、プロセスの途中で何かを待っている場合、これはうまく機能しません。ただし、さまざまな状況に対応するように変更することもできます。

import time, sys, pexpect


some_function():
    child = pexpect.spawn('some command here')

    if debugging:  # Just in case you also want to see the output for debugging
        child.logfile = sys.stdout

    # Do stuff
    child expect('some regex')
    child sendline('some response')

    sleep_count = 0  # For tracking how long it slept for.
    acceptable_duration = 120  # The amount of time that I'm willing to wait

    # Note that apparently solaris can take a while to reply to isalive(),
    # so the process may go a lot longer than what you set the duration to.

    while child.isalive():
        if sleep_count > acceptable_duration
            sys.stderr.write("Useful text explaining that the process never exited."
            sys.exit(1)
        time.sleep(1)
于 2018-11-14T17:53:13.820 に答える