0

I need to be able to call python scripts via execfile() from outside the working directory without specifying the relative file path each time through the interpreter.

instead of:

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

I need to call:

execfile("HelloWorld.py")

is there a sys.path I can add this to that makes this work? The directories are fixed, as are the locations of the working directory and the file. The expectation is that a user can drop a file into the UserScripts directory and expect to be able to call it through the interpreter without the relative file path.

john.dennis
  • 56
  • 2
  • 7

2 Answers2

1

The script below assumes that HelloWorld.py is in the same directory as your executable.

import os.path
import sys

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

However, if you have a subdir where you keep snippets (let's call it '../UserSnippets') you can specify the path relative to the script that contains the execfile:

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

Using os.path.join keeps the code portable ( I hope, I only tested on my Mac ).

Mark
  • 4,249
  • 1
  • 18
  • 27
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));
});
Jeff Hardy
  • 7,632
  • 24
  • 24