0

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?

2 Answers 2

5

Base the path off the __file__ variable:

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

configfile = os.path.join(scriptpath, configfilename)
Sign up to request clarification or add additional context in comments.

6 Comments

I've tried this solution but the behaviour stays the same: the scripts works perfectly if I manually load it and won't work if I put it in rc.local
@Pitto: What is the value of scriptpath when you run the script from rc.local? Is the error still the same?
That's a very good question! How can I check it? The main pain about rc.local is that I can't easily understand what is going wrong there... If I manually run /etc/rc.local it works without a minimum problem but at restart the script is not running (I've tried ps aux | grep script.py)
@Pitto: Use open('/tmp/myscript.log', 'a').write('scriptpath: {0}\n'.format(scriptpath)), then check /tmp/myscript.log once it is created to see.
@Pitto: Then either your code is not run at all, or there was another error in your code.
|
1

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

2 Comments

Sounds tasty! Since my script is an endless loop maybe I should add & at the end, right?
Sorry for the (very) late reply. You could add the &, but personally I would modify the Python script to run as a daemon instead. For an example, see: jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python

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.