使用CommandRunn执行java程序

2024-10-06 13:37:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从python脚本中执行一个带有命令行参数的java程序。我在python中使用CommandRunner并调用其execute()方法,如下所示:

result = remote_command_runner_util.CommandRunner(command, host, user).execute()

我无法执行上面的命令调用,当传入命令的输入参数,如java com.test.helloWorld,并且带有一些有效的用户和主机变量时。你知道吗

是否可以使用CommandRunner从Python调用java程序?(这是我唯一的选择)。你知道吗


Tags: 方法命令行命令程序脚本hostexecute参数
1条回答
网友
1楼 · 发布于 2024-10-06 13:37:35

唯一重要的技巧(从安全性的角度来看)是安全地转义参数向量如果使用subprocess(因为它允许shell=False)是可以避免的,但是使用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()

…之后用作:

executeCommand(['java', '-jar', '/path/to/remote.jar', 'com.test.helloWorld'], host, user)

相关问题 更多 >