0

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.

2
  • Sounds like noexec is set Commented Jun 15, 2020 at 11:43
  • The script is in my home directory. And there is noexec set. Commented Jun 15, 2020 at 15:02

2 Answers 2

1

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 ...")
Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

I am still getting the same error. I am running my script in this way so that it uses the virtual environment python "sudo ~/.virtualenvs/myenv/bin/python myscript.py"
for using the virtual environment you have to activate it first. it is either "source [venv name]/bin/activate" if it is made with pip or "conda activate [venv name]" if it is made with conda
I used virtualenv and virtualenvwrapper. So I activate it with command "workon myenv". But still I am even telling which python it needs to use by giving path to the python.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.