0

I am new to python and linux. Below is the issue I am having.

If I open terminal window and go to directory that has my .py file and run the script everything works fine.

If I try running the script from any other directory using path to the .py file I get an error saying it couldnt find the external config.py file my script uses.

example: My a.py script and config.py are in /home/pi/m

If I am in directory pi@raspberrypi:/home/pi/m and call my .py file everything works

If I am in directory pi@raspberrypi:/ and run command python /home/pi/m/a.py the script doesn't execute and states it can't find my config.py file

What causes this behavior and how do I fix it?

taras
  • 6,566
  • 10
  • 39
  • 50
PL76
  • 83
  • 12

2 Answers2

0

I tried what you are speaking of.It works on my system.Assuming you are doing import config.

[raa@raa ~]$ python ./Desktop/test.py
Ok
[raa@raa ~]$ python ./Desktop/test.py
Config
Ok
[raa@raa ~]$ python /Desktop/test.py
python: can't open file '/Desktop/test.py': [Errno 2] No such file or directory
[raa@raa ~]$ 

I am doing this in test.py

#!/usr/bin/env python3
import config

print('Ok')

And this in config.py:

#!/usr/bin/env python3

print('Config')
Milos Grujic
  • 544
  • 6
  • 15
0

Add this to the top of a.py:

import os, sys
sys.path.append(os.path.realpath(__file__))

This will extend the search for modules to be imported to the local folder of a.py.

hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51