3

My first question on stackoverflow!

I'm trying to figure out how I can start an external program that requires the user to interact with it, say vi, nano, ssh, telnet etc. and return to the Python script when the program exits.

I don't want to use send/expect or automate the external program at all, just start it, use it as normal and then return to the script. I guess bash seems like a more natural way to do this, but I was hoping to get it done in Python.

zondo
  • 19,901
  • 8
  • 44
  • 83
jamdoran
  • 41
  • 3
  • @PadraicCunningham: Read the second paragraph. He doesn't want to interact with it; he wants to pass it straight to the user. – zondo May 11 '16 at 11:16

2 Answers2

1

use the integrated subprocess module. It works quite well with interactive applications. subprocess.call starts an application and is blocking until the application exits.

e.g. starting vi and after exit it starts a connection to 127.0.0.1 over ssh:

import subprocess
subprocess.call(["vi"])
subprocess.call(["ssh","127.0.0.1"])
Günther Jena
  • 3,706
  • 3
  • 34
  • 49
  • I tested this solution with vim, ssh, telnet, nano and bash. It works quite well! – werkritter May 11 '16 at 11:16
  • Thats works perfectly. Many thanks. – jamdoran May 12 '16 at 21:53
  • is there anyway to do this when writing to stdin through a subprocess.popen? e.g. subprocess.Popen(["/bin/bash"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) and then when I run something interactive it (I dont mean literally) "switches to .call" and back – TheHidden May 16 '20 at 12:57
-1

You can use the subprocess module. An example could look like this:

import subprocess

process = subproces.Popen(
    [
        'path/to/the/executable',
        'optional argument',
        'more optional arguments',
        ...
    ],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
)
out, err = process.communicate()

You can find more here: subprocess

Matthias Schreiber
  • 2,347
  • 1
  • 13
  • 20