使用具有不同PYTHONPATH的多个jython PythonInterpreter对象

时间:2016-02-10 17:51:39

标签: java jython

我遇到了导入失败的隐患,我们最终追溯到使用需要不同PYTHONPATH设置的多个pytest-nodev对象。我有一个看起来像这样的构造函数:

public class Thingy
{
   final private PythonInterpreter pi;

   public Thingy(String pythonPath)
   {
      System.getProperties().setProperty("python.path", pythonPath);
      this.pi = new PythonInterpreter();
   }
   ...
}

问题在于它的两个实例无法正常工作,因为它们依赖于python.path的单一系统属性。奇怪的是,看起来第一个胜出而不是 last 一个,这告诉我可能在Jython中有一些单例代码读取{ {1}} Jython库初始化时的系统属性。

用于说明问题的一些测试代码:

python.path

C:/tmp/test1/tweedledee/foo.py:

import org.python.util.PythonInterpreter;

public class SingletonTest {
    final private PythonInterpreter pi;
    final private String objid;

    public SingletonTest(String id, String pythonPath)
    {
        System.getProperties().setProperty("python.path", pythonPath);
        this.objid = id;
        this.pi = new PythonInterpreter();
    }
    public void exec(String code)
    {
        try
        {
            this.pi.exec(code);
        }
        catch (RuntimeException e)
        {
            System.err.printf("id=%s", this.objid);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SingletonTest dee = new SingletonTest("tweedledee", "c:/tmp/test1/tweedledee");
        dee.exec("import foo");

        SingletonTest dum = new SingletonTest("tweedledum", "c:/tmp/test1/tweedledum");
        dum.exec("import bar");
    }
}

C:/tmp/test1/tweedledum/bar.py:

print "Yay, foo loaded"

并打印此程序

print "Yay, bar loaded"

我通过更改构造函数来修复它,以便在Jython本身中设置Yay, foo loaded id=tweedledumTraceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named bar

sys.path

但如果public SingletonTest(String id, String pythonPath) { this.objid = id; this.pi = new PythonInterpreter(); this.pi.exec(String.format("import sys\nsys.path.append('%s')", pythonPath.replace("\\","/"))); // replace backslashes with fwd slashes so the Python interpreter // doesn't get tripped up (we could also escape them) } 类似于pythonPath,那么这似乎非常容易受到PythonInterpreter的影响。但是,Jython等效的SQL预处理语句似乎并不存在。

是否有更好的方法为单个dummy')\ndo_something_evil()\n个实例设置PYTHONPATH路径,以便每个实例都可以设置不同的PythonInterpreter

0 个答案:

没有答案