0

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.

2 Answers 2

2

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.)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

My guess is raw_input() has been removed from python 3.x (It's not there in 3.4). But nice details. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.