|
1 | | -import subprocess |
2 | | -import sys |
3 | 1 | import PySimpleGUI as sg |
4 | 2 |
|
5 | 3 | """ |
6 | 4 | Demo Program - Realtime output of a shell command in the window |
7 | 5 | Shows how you can run a long-running subprocess and have the output |
8 | 6 | be displayed in realtime in the window. |
| 7 | + |
| 8 | + Copyright 2022 PySimpleGUI |
9 | 9 | """ |
10 | 10 |
|
11 | | -sg.theme('Dark Blue 3') |
12 | 11 |
|
13 | 12 | def main(): |
14 | | - layout = [ |
15 | | - [sg.Output(size=(110,30), background_color='black', text_color='white')], |
16 | | - [sg.T('Promt> '), sg.Input(key='-IN-', do_not_clear=False)], |
17 | | - [sg.Button('Run', bind_return_key=True), sg.Button('Exit')] ] |
18 | | - |
19 | | - window = sg.Window('Realtime Shell Command Output', layout) |
20 | | - |
21 | | - while True: # Event Loop |
22 | | - event, values = window.read() |
23 | | - # print(event, values) |
24 | | - if event in (sg.WIN_CLOSED, 'Exit'): |
25 | | - break |
26 | | - elif event == 'Run': |
27 | | - runCommand(cmd=values['-IN-'], window=window) |
28 | | - window.close() |
29 | | - |
30 | | - |
31 | | -def runCommand(cmd, timeout=None, window=None): |
32 | | - nop = None |
33 | | - """ run shell command |
34 | | - @param cmd: command to execute |
35 | | - @param timeout: timeout for command execution |
36 | | - @param window: the PySimpleGUI window that the output is going to (needed to do refresh on) |
37 | | - @return: (return code from command, command output) |
38 | | - """ |
39 | | - p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) |
40 | | - output = '' |
41 | | - for line in p.stdout: |
42 | | - line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip() |
43 | | - output += line |
44 | | - print(line) |
45 | | - window.refresh() if window else nop # yes, a 1-line if, so shoot me |
46 | | - |
47 | | - retval = p.wait(timeout) |
48 | | - return (retval, output) |
| 13 | + layout = [ |
| 14 | + [sg.Multiline(size=(110, 30), echo_stdout_stderr=True, reroute_stdout=True, autoscroll=True, background_color='black', text_color='white', key='-MLINE-')], |
| 15 | + [sg.T('Promt> '), sg.Input(key='-IN-', focus=True, do_not_clear=False)], |
| 16 | + [sg.Button('Run', bind_return_key=True), sg.Button('Exit')]] |
| 17 | + |
| 18 | + window = sg.Window('Realtime Shell Command Output', layout) |
| 19 | + while True: # Event Loop |
| 20 | + event, values = window.read() |
| 21 | + if event in (sg.WIN_CLOSED, 'Exit'): |
| 22 | + break |
| 23 | + elif event == 'Run': |
| 24 | + sp = sg.execute_command_subprocess(values['-IN-'], pipe_output=True, wait=False) |
| 25 | + results = sg.execute_get_results(sp, timeout=1) |
| 26 | + print(results[0]) |
| 27 | + |
| 28 | + window.close() |
49 | 29 |
|
50 | 30 |
|
51 | 31 | main() |
0 commit comments