How to import a file in PythonCall

I have some python code I’d like to call in Julia. The code is in a file in the same folder as pwd() but no matter what method I use I always get the error ERROR: Python: ModuleNotFoundError: No module named 'x'

The first thing I did was

@pyexec """
from x import x
""" => x
ERROR: Python: ModuleNotFoundError: No module named 'x'

This is being run in a folder with a file named x.py. This line works when run in actual python.

The only partial success I’ve had is with

@pyexec """
import os
os.system("python x.py")
"""

Which runs just fine but I can’t get the class named x out.

What do I do?

This works in Python because it includes . (the current folder) in sys.path by default when running interactively.

In PythonCall, Python is loaded in non-interactive mode (even if Julia itself is interactive) so this doesn’t happen so you can’t by default load Python files in the current directory.

A solution is to add this entry yourself, such as with

pyimport("sys").path.append(pwd())

I suppose PythonCall could be changed so that Python is more similar to an interactive session when Julia is being used interactively.

2 Likes

Thanks a lot!
Is this mentioned in the PythonCall docs anywhere? Seems like a really unintuitive limitation for Python amateurs to figure out.

1 Like

Hm no I don’t think it’s in the docs - feel free to open an issue on GitHub linking to this thread.