Subprocess module: running an interactive shell
Karthik Gurusamy
kar1107 at gmail.com
Sat Mar 14 01:58:19 EDT 2009
On Mar 13, 6:39 pm, Roman Medina-Heigl Hernandez <ro... at rs-labs.com>
wrote:
> Hi,
>
> I'm experimenting with Python and I need a little help with this. What I'd
> like is to launch an interactive shell, having the chance to send first
> several commands from python. I've written the following code:
>
> =============
>
> #!/usr/bin/env python
>
> import sys, subprocess
>
> exe = "/bin/sh"
> params = "-i"
-i says shell to be interactive. So looks like it is directly trying
to read from the terminal.
>
> proc = subprocess.Popen([exe, params], stdin=subprocess.PIPE)
proc = subprocess.Popen([exe,], stdin=subprocess.PIPE)
works for me; but if there is an error 'sh' terminates.
If you want to simulate interactive, explore the pexpect module.
>
> proc.stdin.write("id\n")
>
> while True:
> line = sys.stdin.readline()
> if not line:
note that a simple enter terminates the shell which you may not want.
> break
> proc.stdin.write(line)
>
> sys.exit()
>
> =============
>
> The problem is that when I launch it, python proggy is automatically
> suspended. The output I got is:
>
> roman at rslabs:~/pruebas$ ./shell.py
> roman at rslabs:~/pruebas$ uid=1000(roman) gid=1000(roman) groups=1000(roman)
> roman at rslabs:~/pruebas$
>
> [2]+ Stopped ./shell.py
> roman at rslabs:~/pruebas$
>
> Why and how to fix it? Would you suggest a better and more elegant way to
> do what I want?
As I see it, 'sh' is attempting to read from the keyboard and not from
stdin.
Karthik
>
> Thank you.
>
> --
>
> Saludos,
> -Roman
>
> PGP Fingerprint:
> 09BB EFCD 21ED 4E79 25FB 29E1 E47F 8A7D EAD5 6742
> [Key ID: 0xEAD56742. Available at KeyServ]
More information about the Python-list
mailing list