0

我需要能够从工作目录外部通过 execfile() 调用 python 脚本,而无需每次通过解释器指定相对文件路径。

代替:

execfile("..\\UserScripts\\HelloWorld.py")

我需要打电话:

execfile("HelloWorld.py")

是否有一个 sys.path 我可以添加它以使其工作?目录是固定的,工作目录和文件的位置也是固定的。期望用户可以将文件放到 UserScripts 目录中,并期望能够通过解释器调用它而无需相对文件路径。

4

2 回答 2

1

下面的脚本假定 HelloWorld.py 与您的可执行文件位于同一目录中。

import os.path
import sys

execfile(os.path.join( os.path.dirname(sys.argv[0]), 'HelloWorld.py'))

但是,如果您有一个保存片段的子目录(我们称之为“../UserSnippets”),您可以指定相对于包含 execfile 的脚本的路径:

execfile(os.path.join( os.path.dirname(sys.argv[0]), '..','UserSnippets','HelloWorld.py'))

使用 os.path.join 可以保持代码的可移植性(我希望,我只在我的 Mac 上测试过)。

于 2016-07-14T03:42:54.413 回答
0

I would strongly recommend using a different name (say execscript), which you can add to the scope you execute the user scripts in:

scope.SetVariable("execscript", (CodeContext context, string filename) => {
    Builtins.execfile(context, Patch.Combine("../../Scripts", filename));
});

That will make it appear as a builtin without mucking with the builtins dictionary.

If it has to be execfile, your best bet is going to be to replace the execfile builtin with one that patches up the directory and then calls into the old execfile. Here's some completely untested, uncompiled code that should point you in the right direction:

var engine = Python.CreateEngine();
var builtins = engine.GetBuiltinModule();
builtins.SetVariable("execfile", (CodeContext context, string filename) => {
    Builtins.execfile(context, Patch.Combine("../../Scripts", filename));
});
于 2014-02-28T13:00:26.110 回答