Importing Python modules from different working directory
python
Solution
Actually your example works because checks.py is in the same directory as agent.py, but say checks.py was in the preceeding directory, eg;
agent/agent.py
checks.py
Then you could do the following:
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if not path in sys.path:
sys.path.insert(1, path)
del path
Note the use of `__file__`.
Problem
I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself. For example, I would call ``` python agent.py ``` and agent.py has a number of imports, including: ``` import checks ``` where checks is in a file in the same directory as agent.py ``` agent/agent.py agent/checks.py ``` When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors. How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g. ``` python /home/bob/scripts/agent/agent.py ```