1

I am currently trying to get a Python program to autostart on my Raspberry Pi. The problem is, that the program is reading in a config file, which is located in the same folder as the program itself. So when I run the Program from IDE, it works fine.

If I try to run it from the console (or rc.local) it doesn't find the config file. If I cd into the folder and try to run it, it works fine again.

So how can I tell Python or rc.local to run from inside the folder? I have tried to goolge for a solution, but couldn't find one.

I don't want to adress the config file with it's complete path, because I program and debug on my PC, but use the program on the raspberry, so I would have to change the path every time I switch between devices.

Hopefully someone can help me, thanks in advance.

1
  • 1
    Have you considered putting the config file somewhere in /etc/... and reading it with an absolute path? Commented Nov 8, 2020 at 20:12

2 Answers 2

2

I see several possible approaches here:

  • On the raspberry pi, you can cd to the correct directory before running the python program: cd <destination dir> && python your_program.py, or write a two-line shell script to to this.
  • Pass an optional command line argument to python that contains the absolute path to the config file. If no argument is given, use the current path.
  • Try to auto-detect the environment that the python program is running in (e.g. using gethostname() or by setting an environment variable as shown here).
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I usually use a shell script for this kind of stuff.
0
config_filename = os.path.join(os.path.dirname(sys.argv[0]), f'{config_filename})

will get you the FQN for the config based on where the script is located, works in all environments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.