0

I wrote a python script "Script.py" that works when I copy it into the directory I want to run it in. I run this script a lot, so I wanted to add it to .bashrc so I don't have to copy it into every directory I need to run it in.

So the script is in directory:

/home/pythonscripts/Script.py

Now I want to run this script in the directory:

/home/Documents/Test1/

Part of the script is importing a different file (this is unique to each test case). The location of this file is:

/home/Documents/Test1/equations.py

If I start in the "Test1" directory and run "Script.py" I get the following error:

 File "/home/python/Script.py", line 115, in <module>
     import equations
 ImportError: No module named 'equations'

If I place the script into the directory that I'm running this from (/home/Documents/Test1/), there is no error. What I figure is that the script is looking for the equations.py file in the "/home/python" directory, not the local one where I'm running the script from.

My question is how do I tell the script to look in the local directory for the equations.py file in a general way so that I can run Script.py from any directory and have it know to look in the one it's running in for equations.py?

sasha
  • 7
  • 7
  • You can `import sys` and append the desired path to `sys.path`, or do a relative import – ryugie Apr 13 '17 at 19:03
  • That's just the thing, I can't figure out how to add the directory I'm in to sys.path I could do it if I added exactly the directory I'm in. But then it wouldn't be general enough to when I decide to run the script in the next directory. – sasha Apr 13 '17 at 19:04
  • You can `import os` and try `dir_path = os.path.dirname(os.path.realpath(__file__))` or `cwd = os.getcwd()` – ryugie Apr 13 '17 at 19:09
  • Awesome, thank you very much. That worked! – sasha Apr 13 '17 at 19:13

1 Answers1

0

To get the current working directory (the directory you were in when running the script)

import os
cwd = os.getcwd()

now you can import the file using the full path cwd/myfile.py using importlib (in python 3). for more info see How to import a module given the full path?

as a side note, when working with files and the filesystem, I personally really like working with this package: https://github.com/gabrielfalcao/plant

Community
  • 1
  • 1
polo
  • 1,352
  • 2
  • 16
  • 35
  • Thanks! The first part of your answer was super helpful. And I'm going to read up on the second part to learn more – sasha Apr 13 '17 at 21:10