PyDev自定义解释器脚本不读取Env变量

2024-04-26 19:08:35 发布

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

我在InterpreterInfo的script元素中定义了一个自定义python解释器。我还在那里定义了一些环境变量,当我在pydevui中查看解释器信息时就会看到它们。你知道吗

解释器可执行文件是包装python解释器的shell脚本(tcsh)。它工作正常,只是看不到为解释器设置的环境变量。我原以为这些应该在可执行脚本的环境中设置,但事实并非如此。有没有一种方法可以将为解释器信息定义的变量传递到解释器的可执行脚本中?你知道吗

编辑:

当任何PyDev项目被添加到工作区时,我会修改script元素,以便它用包装python解释器的shell脚本替换python解释器的路径。以下是Java代码,省略了异常处理。你知道吗

private static InterpreterInfo createInterpreterInfo(String interpreter, IProgressMonitor monitor) throws CoreException {
        final File script = PydevPlugin.getScriptWithinPySrc("interpreterInfo.py");
        Tuple<String, String> outTup;
        outTup = new SimplePythonRunner().runAndGetOutputWithInterpreter(interpreter, script.getCanonicalPath(), null, null, null, monitor, "UTF-8");

        String interpreterXml = outTup.o1;
        String replacedInterpreterXml  = interpreterXml;

        //substitute the script for the <executable> element in the XML string
        String executableStartTag = "<executable>";
        String executableEndTag = "</executable>";
        int executableElementStart = interpreterXml.indexOf(executableStartTag) + executableStartTag.length();  
        int executableElementEnd = interpreterXml.indexOf(executableEndTag);

        replacedInterpreterXml = interpreterXml.substring(0, executableElementStart) + interpreter + interpreterXml.substring(executableElementEnd);

        // Add an environment variable
        String xmlEndTag = "</xml>";
        int xmlEndElementStart = replacedInterpreterXml.indexOf(xmlEndTag);  

        replacedInterpreterXml = replacedInterpreterXml.substring(0, xmlEndElementStart) +
                "\n<env_var>" +
                SOME_VARIABLE + "=" + ENV_VAR_VALUE +
                "</env_var>\n" +
                replacedInterpreterXml.substring(xmlEndElementStart);

        return InterpreterInfo.fromString(replacedInterpreterXml, false);
    }

然后包装器脚本执行一些环境设置,并使用命令字符串调用python解释器。当解释器返回时,脚本执行环境分解。脚本无法找到在InterpreterInfo上设置的环境变量,方法是查看shell环境或让python解释器查询其环境。你知道吗

以下是包装器shell脚本的表示:

#!/bin/tcsh

#redirect output to avoid corrupting output to `InterpreterInfo`
echo Env variable SOME_VARIABLE = $SOME_VARIABLE > /log/file #throws error because SOME_VARIABLE is not set
python -c "import os;print os.environ['SOME_VARIABLE']" > /log/file #no value set for SOME_VARIABLE

do_environment_setup

python $*

do_environment_cleanup

Tags: 脚本string定义环境环境变量scriptsomesubstring