8

ビューウィンドウ(コンソール)とコマンドラインの両方を起動するプログラムを作成しようとしています。ビューウィンドウでは、一定の更新が表示されますが、コマンドラインウィンドウはraw_input()、ビューウィンドウに影響を与えるコマンドを受け入れるために使用されます。これにスレッドを使用することを考えていますが、新しいコンソールウィンドウでスレッドを起動する方法がわかりません。どうすればいいですか?

4

3 に答える 3

12

私は@starkに同意します。GUIがその方法です。

純粋に説明のために、スレッド、サブプロセス、およびIPCとして名前付きパイプを使用してそれを行う方法を示す非GUIの非推奨の方法を次に示します。

2つのスクリプトがあります。

  • entry.py:ユーザーからのコマンドを受け入れ、コマンドで何かを実行し、コマンドラインで指定された名前付きパイプに渡します。

    #!/usr/bin/env python
    import sys
    
    print 'entry console'
    with open(sys.argv[1], 'w') as file:
        for command in iter(lambda: raw_input('>>> '), ''):
            print ''.join(reversed(command)) # do something with it
            print >>file, command # pass the command to view window
            file.flush()
    
  • view.py:エントリコンソールを起動し、スレッドで一定の更新を出力し、名前付きパイプからの入力を受け入れて、更新スレッドに渡します。

    #!/usr/bin/env python
    import os
    import subprocess
    import sys
    import tempfile
    from Queue import Queue, Empty
    from threading import Thread
    
    def launch_entry_console(named_pipe):
        if os.name == 'nt': # or use sys.platform for more specific names
            console = ['cmd.exe', '/c'] # or something
        else:
            console = ['xterm', '-e'] # specify your favorite terminal
                                      # emulator here
    
        cmd = ['python', 'entry.py', named_pipe]
        return subprocess.Popen(console + cmd)
    
    def print_updates(queue):
        value = queue.get() # wait until value is available
    
        msg = ""
        while True:
            for c in "/-\|":
                minwidth = len(msg) # make sure previous output is overwritten
                msg = "\r%s %s" % (c, value)
                sys.stdout.write(msg.ljust(minwidth))
                sys.stdout.flush()
    
                try:
                    value = queue.get(timeout=.1) # update value
                    print
                except Empty:
                    pass
    
    print 'view console'
    # launch updates thread
    q = Queue(maxsize=1) # use queue to communicate with the thread
    t = Thread(target=print_updates, args=(q,))
    t.daemon = True # die with the program
    t.start()
    
    # create named pipe to communicate with the entry console
    dirname = tempfile.mkdtemp()
    named_pipe = os.path.join(dirname, 'named_pipe')
    os.mkfifo(named_pipe) #note: there should be an analog on Windows
    try:
        p = launch_entry_console(named_pipe)
        # accept input from the entry console
        with open(named_pipe) as file:
            for line in iter(file.readline, ''):
                # pass it to 'print_updates' thread
                q.put(line.strip()) # block until the value is retrieved
        p.wait()
    finally:
        os.unlink(named_pipe)
        os.rmdir(dirname)
    

試すには、次を実行します。

$ python view.py
于 2012-07-30T15:32:52.443 に答える
7

コンソールまたはターミナルウィンドウを使用するのではなく、問題を再検討してください。あなたがやろうとしているのは、GUIを作成することです。WxやTkinterなど、必要なことを正確に実行するウィジェットを備えたクロスプラットフォームツールキットが多数あります。出力用のテキストボックスとキーボード入力を読み取るための入力ウィジェット。さらに、タイトル、ヘルプ、開く/保存/閉じるなどの素敵なフレームでそれらをラップすることができます。

于 2012-07-29T21:14:39.690 に答える
1

更新された回答:

import subprocess
command = "dir"
subprocess.run(["cmd.exe", "/c", "start", f"{command}"], timeout=15)

「cmd.exe」 -Windowsを使用している場合、Windowsは二重引用符のみを認識します。
「/c」 -「dir」(たとえば)文字列を送信した後、「Returnを送信」と言います。
"start" -新しいコンソールウィンドウを開くと言います...Pycharmでデバッグしている場合でも:
)f"コマンド" -f-stringsを使用してアセンブル文字列を送信しますPython3.6+
(タイムアウトはオプション)

于 2020-09-05T00:30:10.007 に答える