【问题标题】:Executing a java program using CommandRunner使用 CommandRunner 执行 java 程序
【发布时间】:2018-04-21 17:11:39
【问题描述】:

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

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

当为命令传递输入参数(例如java com.test.helloWorld)并带有一些有效的用户和主机变量时,我无法执行上述命令调用。

是否可以使用 CommandRunner 从 Python 调用 java 程序? (这是我唯一可用的选项)。

【问题讨论】:

  • 一个很好的问题可以准确地显示您遇到的错误,并且最好让其他人自己查看问题并测试他们提出的修复是否有效,如minimal reproducible example 中所述定义。您的类似乎不太可能真正位于相关远程计算机上的默认 CLASSPATH 上。

标签: python


【解决方案1】:

唯一重要的技巧(从安全角度来看)是安全地转义您的参数向量 - 如果使用 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)

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 2016-01-29
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多