Skip to content
Advertisement

python3 import error: while running with sudo -u python3

For my python script I need to change the user. Therefore I start the script with: sudo -u eval python3 run_aufgabe2.pythere is no problem running the script until I import modules from the same directory, then I get an import-error:

$ Traceback (most recent call last):
$     File "run_aufgabe2.py", line 5, in <module>
$ import aufgabe2
$ ImportError: No module named 'aufgabe2'

Running the script without sudo -u eval, the import is working and the script is running without errors. I first thought about a permission problem, maybe the the user eval can not read the file aufgabe2.py, so I changed the rights:

$ -rwxrwxrwx 1 root root 3583 Apr 12 09:08 aufgabe2.py
$ -rwxrwxrwx 1 root root    0 Apr 12 09:08 __init__.py
$ -rwxrwxrwx 1 root root  432 Apr 12 09:43 run_aufgabe2.py

But still the same error, I can not think of anything more, but I am sure I am missing something.


Edit 1:

I have to kinds of shell scripts to run the python scripts.

Bash script for simple scripts:

#!/bin/bash
cd $1
sudo -u eval python3 $2

Expect script for dynamic userinputs:

#!/usr/bin/expect
cd [lindex $argv 0]
spawn sudo -u eval python3 [lindex $argv 1]
#[...]

As @FlyingTeller hast mentioned in his commands, I have the option to add the current working dir to the PYTHONPATH variable. I couldn’t get this running, maybe someone can help me with the shell scripts.

Thanks a lot!

Advertisement

Answer

As @FlyingTeller has mentioned, usually the directory you are running the script in, get’s added to sys.path. Seems like sudo -u eval messed with that somehow. The solution is adding path manually:

import sys
sys.path.append(".")
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement