How can I exec an interactive shell from Jython?

2019-06-05 20:34发布

问题:

I need some example Jython, or Java, code to exec an interactive OS shell (/bin/sh). Our development environment is Java on Linux. What I would like to do is provide a means for developers to write Jython scripts, and then drop into a shell, which allows them to inspect the system. The reason I need to exec this from Jython or Java--as opposed to just wrapping all this in a shell script--is that we use Java load some libraries which I need to keep loaded while the interactive shell is running. If the JVM were to terminate before the interactive shell runs, some of our custom hardware would be reset.

I have looked at the Jython subprocess module. However, most of what I have seen will only run and wait on a subrocess to terminate (ie non-interactive). None of the examples show how to the shell can be invoked interactively. The same is true of most of the Java java.lang.Runtime.exec() examples I've seen.

回答1:

What is wrong with this simple jython code, is that the stdin, stdout do not work as we expect

import subprocess
import os          
subprocess.call([os.environ.get('SHELL', '/bin/sh'), '-i'])

Assuming that we want to spawn the shell on the tty, the following seems to give better results:

import os
import subprocess

subprocess.call([os.environ.get('SHELL', '/bin/sh') +
    ' -i < /dev/tty > /dev/tty 2>&1'], shell=True)

This will run the shell within another subshell, that replaces the crippled stdin, stdout streams with the active tty.