Hari
Hari

Reputation: 51

Invalid Syntax error for running python script with sudo

I am executing a python script from my terminal by python myscript.py. Then I am asked for the password as in my code I am using os.system("sudo some_command_here"). But when I run the same code from the terminal by sudo python myscript.py. it shows me SyntaxError: invalid syntax. if I comment out that line just to check if it resolves, but I still get the same error in some other line of code. Am I doing something wrong, why it gives me that error.

Upvotes: 0

Views: 2583

Answers (2)

bkakilli
bkakilli

Reputation: 519

If you are using a virtual environment, then make sure all python interpreter instances are pointing to your python binary in your virtual environment.

The first and obvious instance you should change is:

# sudo python myscript.py
sudo /path/to/virtualenv/bin/python myscript.py

Then change all instances inside your myscript.py. I presume that the "some_command_here" in your example is also a python call.

"""myscript.py"""

# os.system("sudo python arg1 arg2 ...")
os.system("sudo /path/to/virtualenv/bin/python arg1 arg2 ...")

Upvotes: 1

themozel
themozel

Reputation: 502

In case you are using a virtual environment for your python, it might be that your system's python version is different than the one you have in the venv and the sudo command always uses the system version. Using python3 instead of python for the sudo may solve the problem.

Upvotes: 0

Related Questions