v / examples / process / wrapping_interactive_python.v
44 lines · 43 sloc · 1.2 KB · 4687f8c1f75aee001219d7432990c0d9f42e9471
Raw
1import os
2import time
3import term
4
5python_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}
9mut p := os.new_process(python_exe)
10defer {
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
17p.set_args(['-i', '-q', '-u'])
18p.set_redirect_stdio()
19p.run()
20dump(p.pid)
21println('This is a simple V wrapper/shell for the Python interpreter.')
22println('Try typing some python code here, or type `bye` to end your session:')
23for 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