How to change the working directory for a shell script

Quick and dirty:

In your start up script instead of just executing the python script, use cd first.

#!/bin/sh

cd /home/username/projectname &&
python ./scriptname.py

There are a couple of ways around this directly in your Python script.

  1. If your script is always going to be in "/home/username/projectname/subfolder", you can simply add that to your search path inside Python:

    import sys
    sys.path.append("/home/username/projectname/subfolder")
    

    I suspect, however, that you might have this in multiple "projectname" directories, so a more generic solution is something like this:

    import sys
    import os
    sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), "subfolder"))
    

    This finds the directory where the Python script is (in sys.argv[0]), extracts the directory part, appends "subfolder" onto it, and puts it into the search path.

    Note that some operating systems may only give the executable name in sys.argv[0]. I don't have a good solution for this case, perhaps someone else does. You may also need to inject a os.path.abspath() call in there if sys.argv[0] has a relative path, but play around with it a bit and you should be able to get it working.

  2. Similar to the above answer, you can have the Python script change directories all by itself with no need for a wrapper script:

    import os
    os.chdir("/home/username/projectname")
    

An even faster, dirtier way of doing it (with a subshell):

$ ( cd my/path/to/folder && python myprogram.py )