I am trying to execute a java program with a command line argument from inside a python script. I am using CommandRunner within python and invoking its execute() method as follows:
result = remote_command_runner_util.CommandRunner(command, host, user).execute()
I am unable to execute the above command call, when passing in input parameter such as java com.test.helloWorld for the command and with some valid user and host variables.
Is it possible to invoke java program from Python using CommandRunner? (that is the only option available for me).
-
Possible duplicate of run Java program with jar from PythonMiriam– Miriam2018年04月21日 17:14:59 +00:00Commented Apr 21, 2018 at 17:14
-
A good question shows exactly what error you get, and ideally lets someone else see the problem for themselves and test if their proposed fix works, as described in the minimal reproducible example definition. It seems unlikely that your classes are really on the default CLASSPATH on the remote machine in question.Charles Duffy– Charles Duffy2018年04月21日 17:20:06 +00:00Commented Apr 21, 2018 at 17:20
1 Answer 1
The only important trick (from a security perspective) is to safely escape your argument vector -- something that's avoided if using subprocess (since it allows shell=False), but unavoidable with CommandRunner.
import pipes, shlex
if hasattr(pipes, 'quote'):
quote = pipes.quote # Python 2
else:
quote = shlex.quote # Python 3
def executeCommand(argv, host, user):
cmd_str = (' '.join(quote(arg) for arg in argv))
return remote_command_runner_util.CommandRunner(cmd_str, host, user).execute()
...thereafter used as:
executeCommand(['java', '-jar', '/path/to/remote.jar', 'com.test.helloWorld'], host, user)