Reputation: 1235
I have a simple python script, test.py:
x = input("Enter string")
print("Entered str: ", x)
I want to run the script as another user; lets call him scratch:
sudo -u scratch python test.py
The program waits for the console input. When I enter "abc", I encounter the following error:
Enter stringTraceback (most recent call last):
File "test.py", line 1, in <module>
x = input("Enter string")
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
I am not sure about the reason behind this and the fix for it.
Upvotes: 0
Views: 297
Reputation: 184270
input
behaves differently in Python 2.x and 3.x. The other account has Python 2.x set as its default, or has a Python 2.x executable first in its PATH
. Your usual account, on the other hand, is using a Python 3.x executable. Probably the best way to do this is to use the full path to the Python executable you want to use i the script's "shebang" line. For example:
#!/usr/bin/python3
(This path may need adjusting for your system. Try typing which python
in your account to see what it's using.)
Upvotes: 2
Reputation: 12092
The issue is the code is using input()
in a Python 2.7 environment (the other users' default python version probably). Try using raw_input()
instead.
input()
in a 2.7 behaves as a raw_input()
followed by an exec()
which is why it throws the NameError
.
The code would run fine on a Python 3.x interpreter.
Upvotes: 1