admin管理员组

文章数量:1287942

I have a Python package that is supposed to be used interactively, mostly from a debugger. (It is indented for the classroom, and the students are expected to poke around.)

When the package tutorials are loaded into the Spyder IDE, the current folder is set to the folder in which the tutorial lives. On the other hand, when the tutorial is run from a command line using py, it is typically from the top folder of the package.

Consequently, I use a "context.py" file stored in the tutorials folder that inserts a couple of paths.

import os
import sys
sys.path.insert(0, os.path.abspath("."))
sys.path.insert(0, os.path.abspath(".."))

and each tutorial includes import context.

This device modifies the path for the running python so that it sees the source files of the package.

Disconcertingly, it feels hacky, and I'm wondering if there is a better way?

The trick with the "context" file works. However, it feels ad hoc, and the question is: is there a more pythonic way of doing this?

I have a Python package that is supposed to be used interactively, mostly from a debugger. (It is indented for the classroom, and the students are expected to poke around.)

https://github/PetrKryslUCSD/pystran

When the package tutorials are loaded into the Spyder IDE, the current folder is set to the folder in which the tutorial lives. On the other hand, when the tutorial is run from a command line using py, it is typically from the top folder of the package.

Consequently, I use a "context.py" file stored in the tutorials folder that inserts a couple of paths.

import os
import sys
sys.path.insert(0, os.path.abspath("."))
sys.path.insert(0, os.path.abspath(".."))

and each tutorial includes import context.

This device modifies the path for the running python so that it sees the source files of the package.

Disconcertingly, it feels hacky, and I'm wondering if there is a better way?

The trick with the "context" file works. However, it feels ad hoc, and the question is: is there a more pythonic way of doing this?

Share Improve this question asked Feb 22 at 18:06 Petr KryslPetr Krysl 1
Add a comment  | 

1 Answer 1

Reset to default 0

Disconcertingly, it feels hacky(...)

sys.path documentation says that

A program is free to modify this list for its own purposes. Only strings should be added to sys.path; all other data types are ignored during import.

so such usage is explicitly allowed.

本文标签: Is there a better way of making Python aware of module sourcesStack Overflow