| 1 | import os |
| 2 | import time |
| 3 | import term |
| 4 | |
| 5 | python_exe := os.find_abs_path_of_executable('python') or { |
| 6 | eprintln('This example needs a python executable in your PATH. Please install Python to see it in action.') |
| 7 | exit(1) |
| 8 | } |
| 9 | mut p := os.new_process(python_exe) |
| 10 | defer { |
| 11 | dump(p.code) |
| 12 | p.close() |
| 13 | p.wait() |
| 14 | } |
| 15 | // The Python flags here, are needed to reduce clutter and buffering. |
| 16 | // See https://docs.python.org/3/using/cmdline.html |
| 17 | p.set_args(['-i', '-q', '-u']) |
| 18 | p.set_redirect_stdio() |
| 19 | p.run() |
| 20 | dump(p.pid) |
| 21 | println('This is a simple V wrapper/shell for the Python interpreter.') |
| 22 | println('Try typing some python code here, or type `bye` to end your session:') |
| 23 | for p.is_alive() { |
| 24 | // check if there is any input from the user (it does not block, if there is not): |
| 25 | if os.fd_is_pending(0) { |
| 26 | cmd := os.get_raw_line() |
| 27 | if cmd.len == 0 { |
| 28 | println('closed stdin detected, perhaps due to Ctrl-D...exiting') |
| 29 | break |
| 30 | } |
| 31 | if cmd.trim_space() == 'bye' { |
| 32 | println('Goodbye...') |
| 33 | break |
| 34 | } |
| 35 | p.stdin_write(cmd) |
| 36 | } |
| 37 | if oline := p.pipe_read(.stdout) { |
| 38 | print(term.bright_yellow('python stdout: ') + term.bold(oline)) |
| 39 | } |
| 40 | if eline := p.pipe_read(.stderr) { |
| 41 | eprint(term.red('python stderr: ') + eline) |
| 42 | } |
| 43 | time.sleep(20 * time.millisecond) |
| 44 | } |
| 45 | |