简体   繁体   中英

CLI Front End with Python: How to pass string to a running process?

How to send string/data to STDIN of a running process in python?

i'd like to create a front end for a CLI program. eg. i want to pass multiple string to this Pascal application:

program spam;
var a,b,c:string;
begin
while e <> "no" do
begin
    writeln('what is your name?');
    readln(a);
    writeln('what is your quest?');
    readln(b);
    writeln('what is your favorite color?');
    readln(c);
    print(a,b,c);
end;
end.

how do i pass string to this program from python (using subprocess module in python). thankyou. sorry for my english.

If you want to control another interactive program, it could be worth trying the Pexpect module to do so. It is designed to look for prompt messages and so on, and interact with the program. Note that it doesn't currently work directly on Windows - it does work under Cygwin.

A possible non-Cygwin Windows variant is WinPexpect , which I found via this question . One of the answers on that question suggests the latest version of WinPexpect is at http://sage.math.washington.edu/home/goreckc/sage/wexpect/ , but looking at the modification dates I think the BitBucket (the first link) is actually the latest.

As Windows terminals are somewhat different to Unix ones, I don't think there is a direct cross-platform solution. However, the WinPexpect docs say the only difference in the API between it and pexpect is the name of the spawn function. You could probably do something like the following (untested) code to get it to work in both:

try:
    import pexpect
    spawn = pexpect.spawn
except ImportError:
    import winpexpect
    spawn = winpexpect.winspawn

# NB. Errors may occur when you run spawn rather than (or as
# well as) when you import it, so you may have to wrap this 
# up in a try...except block and handle them appropriately.
child = spawn('command and args')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM