我有一个 Python 3.5 脚本,我想在我的 Code Composer 构建中将其作为预构建步骤调用。明确地说,它应该作为(我的项目)> Properties > CCS Build > Steps > Pre-build steps 中的条目之一运行。
脚本当前以井号 #!/usr/bin/env python3 开头,但我可以更改它。
在 Linux 上,我可以将脚本调用为 ../prebuild.py ../output_file。这在 Windows 10 上失败了:
"C:\\ti\\ccsv6\\utils\\bin\\gmake" -k all
../prebuild.py ../output_file
makefile:217: recipe for target 'pre-build' failed
process_begin: CreateProcess(NULL, env python3 C:\path\to\prebuild.py ../output_file, ...) failed.
make (e=2): The system cannot find the file specified.
路径分隔符对此完全没有影响。
我还尝试了 python3 ../prebuild.py ../output_file。这在 Windows 10 上不起作用,因为没有 python3 可执行文件。 Python 3 安装为 python.exe。在 Linux 上使用 python 失败,因为当然 Python 3 安装为 python3,而 python 指的是 Python 2。
我还尝试了 py ../prebuild.py ../output_file。这在 Linux 上失败,因为没有 py 可执行文件。
是否有一种跨平台的方式来调用可用于 Eclipse 预构建步骤的 Python 3 脚本?我想避免要求开发人员修改他们的发行版/Python 安装。
我正在使用基于 Eclipse 的 Code Composer Studio 6。我希望对此的任何答案都适用。
上下文
我想要实现的其中一件事是将当前 Git 提交的 SHA1 插入到一个文件中。 accepted answer这样做是通过解析 Git 输出来生成文件作为构建过程的一部分。我有一个 Python 脚本可以在 Windows 和 Linux 上执行此操作,因此我需要一种方法来调用它作为 Eclipse 构建过程的一部分。
请您参考如下方法:
拥有一个可在 Python 2 和 3 下运行的包装器脚本,以使用正确的 Python 版本检测和运行脚本。然后,Eclipse/CCS 预构建步骤可以是 python ../wrapper.py(可能带有额外的参数,例如 ../prebuild.py args)。
您可以只检查它是在 Windows 还是 Linux 上运行,以及它运行的是哪个版本的 Python。如果它在 Linux 上运行并且运行错误的 Python 版本,请运行 subprocess.call(['python3','prebuild.py'])。要检查 Python 版本和操作系统使用:
import os, sys, subprocess
if sys.version_info[0] < 3 and os.name == 'posix':
subprocess.call(['python3','../prebuild.py'])
sys.exit()
else:
subprocess.call(['python','../prebuild.py'])
sys.exit()
更通用的脚本可能 check if the interpreter已经是正确的,如果是,则尝试传递参数:
import sys
if sys.version_info[0] >= 3 and sys.version_info[1] >= 3:
subprocess.call([sys.executable] + sys.argv[1:]
否则包装器可以迭代可能的解释器列表,直到成功,例如:
interpreters = [["py", "-3"], ["python3"]]
for interp in interpreters:
# Try a subprocess.call(...) as above. Detect bad return codes (eg. py failed) or OSErrors (ie. command wasn't found).
success = False
try:
success = subprocess.call(...) == 0
except OSError:
pass
if success:
break
