Pitto
Pitto

Reputation: 8579

Python script on linux and autostart at boot path

I've made a script in Python and it works without problems. Since I've added a configuration file (I've used a parser) it stopped starting at boot (I have it in my rc.local file with its absolute path).

Investigating further I've found out that I need to specify the absolute path of the configuration file in the python script or it isn't working.

I've like it to work checking simply in the folder where the script file sits.

I mean:

if my script.py is in home folder I'd like it to check for its configuration file in the same folder... If it's in /home/user I'd like it to check in /home/user.

How can I achieve this keeping in mind that rc.local is run by root user with some ENV variables that are different from my normal user's?

Upvotes: 0

Views: 859

Answers (2)

faucamp
faucamp

Reputation: 121

As an alternative to Martijn's answer above, you could simply modify your rc.local file to change the current working directory to that of your script's and then run it without its absolute path. This doesn't require you to modify the Python script itself.

In other words, change your rc.local from:

python /home/user/your_script.py

to

pushd /home/user
python your_script.py
popd

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121376

Base the path off the __file__ variable:

import os.path
scriptpath = os.path.abspath(os.path.dirname(__file__))

configfile = os.path.join(scriptpath, configfilename)

Upvotes: 5

Related Questions