Forums

my command line python app is not treating inputs as strings

I wrote a small script that uses the Bash command line interface to input information into a database. The script works beautifully on my home desktop, but I would like to move it to the PythonAnywhere platform. My problem is that when I attempt to use the script, as soon as I type something at the prompt, I get the following error:

00:40 ~/enterjobs $ python enterjobs.py

Search for client by name
Client >>  Bob
Traceback (most recent call last):
  File "enterjobs.py", line 263, in <module>
    main()
  File "enterjobs.py", line 261, in main
    ej_state.prompt()
  File "enterjobs.py", line 128, in prompt
    self.current_state["handler"](input(self.current_state["prompt"]))
  File "<string>", line 1, in <module>
NameError: name 'Bob' is not defined
00:41 ~/lch/enterjobs $

I typed "Bob" without quotes, hit enter, and Python threw an exception and quit. If I type "Bob" with quotes and quote the rest of my input, my script works perfectly. But I do not want to quote everything I enter into my script's input. I'm guessing the issue arises from the implementation of the online Bash console on PythonAnywhere. Is there are workaround? I would even be happy to use some kind of hack to the builtin Python input() function. I just don't want to have to quote everything I type.

Use raw_input() instead of input().

So I figured out how to hack the input() function by adding the following code to the top of my script:

old_input = input
def input(s)
    try:
        return old_input(s)
    except NameError as e:
        return e.__str__()[6:-16]

Basically, I'm overriding the input() function with a custom function that catches the NameError and extracts the input from the NameError exception string. I'd still be happy to learn of a better solution.

Interesting hack, but you don't need it because input() is for interpreted inputs (python statements), not just text.

From python 2 docs: input([prompt]) is quivalent to eval(raw_input(prompt)).

Oh, I see. I'm running Python 2.7.6, but my script was developed on Python 3.6. I now see it works fine if I run my script on python3.6. Thanks Astronoms!

Sorry, I forgot that raw_input() was renamed to input() in Py3. Also I suggest to apply the .strip() function for input strings ;)