简体   繁体   English

与使用Python / Gradle转义字符有关的跨平台问题

[英]Cross-platform issue related to escaping characters with Python / Gradle

I am having cross-platform issues when calling a Gradle JavaExec task from Python. 从Python调用Gradle JavaExec任务时遇到跨平台问题。 One sub-project has an application to generate some output and it accepts command line arguments to do so. 一个子项目有一个应用程序来生成一些输出,并且它接受命令行参数来这样做。

Gradle task: Gradle任务:

task run(type: JavaExec) {
    main = 'generator.myGenerator'
    classpath = sourceSets.main.runtimeClasspath
    if (System.getProperty("exec.args") != null) {   
        args System.getProperty("exec.args").split()
    }
}

On the command line, this is run by typing eg: 在命令行上,通过键入例如以下内容来运行:

./gradlew run -Dexec.args="--minBound 5 --maxBound 8"

Another sub-project wants to run this generator and steps into the appropriate directory and makes a subprocess call, passing the relevant parameters: 另一个子项目要运行此生成器并进入相应的目录,并通过传递相关参数来进行子流程调用:

Python code: Python代码:

args = ('-Dexec.args=\"--minBound\ ' + str(min_bound) +
                    '\ --maxBound\ ' + str(max_bound) + '\"')


subprocess.check_call(['./gradlew', 'run', args])

This works well under Cygwin, but fails under Ubuntu 16.04 LTS. 这在Cygwin下效果很好,但在Ubuntu 16.04 LTS下失败。 The error message is: 错误消息是:

:generator:run
maxBound\ is not a recognized option

This error message is generated by the command line parser of the generator. 此错误消息是由生成器的命令行解析器生成的。 The issue is clearly that the backslash that Cygwin requires to escape the spaces cause problems. 问题很明显是Cygwin逃逸空间所需的反斜杠会引起问题。 Removing the escapes does not seem to fix the problem on Linux and I am not sure what it needs. 删除转义符似乎无法解决Linux上的问题,而且我不确定它需要什么。

I am using Python 3.5. 我正在使用Python 3.5。

All in all, I am not sure if this is an issue of escapes in Linux vs. Windows, if it is a Gradle issue, or if it has something to do with Python. 总而言之,我不确定这是Linux还是Windows中的转义问题,是否是Gradle问题,或者是否与Python有关。 Any help would be greatly appreciated. 任何帮助将不胜感激。

After some tinkering, I noticed that by putting all arguments in a list and turning them into a string with 经过一番修补后,我注意到通过将所有参数放入列表并将它们转换为

args = '\ '.join(argList) 

would work on Cygwin and 将在Cygwin上工作,

args = ' '.join(argList) 

would work on Linux. 将在Linux上运行。 However, I did not find a nice platform-independent way for this solution without detecting which OS was being used. 但是,在未检测到正在使用哪个操作系统的情况下,我没有找到一种适用于该解决方案的很好的平台无关方法。 Instead, I found a solution based on raw strings that works well on both Cygwin and Linux. 相反,我发现了一种基于原始字符串的解决方案,该解决方案在Cygwin和Linux上均能很好地工作。

argRaw = r"-Dexec.args= --minBound {} --maxBound {}"
args = argRaw.format(min_bound, max_bound)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM