Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Python script from Bash file causes Import errors

Tags:

python

linux

bash

I wrote a simple bash script to run a game I am making in Python. However, when I do this, it gives me an import error when trying to import custom modules.

Traceback (most recent call last):
  File "/home/user/Projects/Test/game.py", line 7, in <module>
    import boot, splash, menu, game, player, options
ImportError: No module named 'boot'

I checked the permissions on the folder containing the modules and they are accessible. If I just run the game.py in Terminal as:

python3.4 game.py

Then everything works perfectly fine. No import errors or anything. Just when I run it as the Bash file. For reference, here is the Bash file I am using:

#!/bin/bash
STRING="Launching game..."
PYTHON="/usr/bin/python3.4"
GAME="/home/user/Projects/Test/game.py"
echo $STRING
$PYTHON "$GAME"

EDIT: It appears to be an absolute/relative path issue as to where the Bash file is and the Python file. Running the Bash file, since the Python file is using relative path, makes it so it does not know where the source of the custom modules are.

like image 938
Gramps Avatar asked Nov 01 '22 20:11

Gramps


1 Answers

If you are concerned about relative vs. absolute paths (which do sound like they could be the potential cause here), I would recommend doing something like my code below to ensure that you use relative paths in the bash script also.

Essentially, you switch the cwd to the directory containing the game file, but leverage pushd and popd to ensure that the switch doesn't affect anything else. The redirection to /dev/null is to suppress output that comes from pushd/popd which is usually just extra noise in a script situation.

#!/bin/bash
STRING="Launching game..."
PYTHON="/usr/bin/python3.4"
GAME_ROOT="/home/user/Projects/Test"
GAME="game.py"

pushd . > /dev/null 2>&1
cd $GAME_ROOT

echo $STRING
$PYTHON "$GAME"

popd > /dev/null 2>&1
like image 133
khampson Avatar answered Nov 15 '22 05:11

khampson