So i am working on a command line program in python, and one of my commands is "help", which prints info on the various commands as you would expect. However, when i enter "help" using the input() method, and then split it, i get this error
Traceback (most recent call last):
File ..., line 385, in <module>
cmd(userinput)
File ..., line 292, in cmd
parts = line.split(' ', 1)
AttributeError: '_Helper' object has no attribute 'split'
and when i have it print what user just entered i get
Type help() for interactive help, or help(object) for help about object.
Why on earth is python executing its shell help inside of my program?
for reference, the relevant bits of code are
def cmd(line):
print line
parts = line.split(' ', 1)
cmd(input(">"))
Because that's what input() in 2.x does: it tries to evaluate the string entered. Use raw_input() instead.
Do not use the input function (in Python 2.x) ever, use raw_input and parse the returned string. input will eval the string the user entered (same as eval(raw_input('>'))) and there is a global named "help", which is evaluated. Thus the behavior you see.
Python 3 has only input which acts like raw_input (does not eval), so on Python 3 you should use input.
There are two things going on here:
As others have pointed out, input on Python 2.x evaluates the input and returns the result. Since help is a builtin python function, python returns the help function.
The help function is actually an instance of site._Helper. site._Helper_ overrides the default __repr__ on object. Now when print turns help into a string, object.__str__ will be called, which will turn around and invoke _Helper.__repr__, which will print the help mesage. That is why you see the python help message when you print it.
Of course, you should use raw_input instead of input.
Related
I am trying to create a variable to be used in more than one place to print a line of script
I tried using this to print: print(helped), didn't work, it gave the error you see. I tried doing this: print helped(), gave a syntax error
def helped():
print('''Type
Type
Type''')
weirdness = input('''What function would you like to run?
Type "Help" for possible commands ''')
if weirdness.upper() == "HELP":
print (helped)
When I enter "helped" upon being prompted, I get:
What function would you like to run?
Type "Help" for possible commands helped
I think you need a bit of help
instead of getting the print statement
How do i resolve the issue such that this wont happen?
In Python when calling a function, you must use the parentheses. So since your function's name is helped, you should call it like this:
print( helped() )
You should do this regardless of whether your function has parameters.
On a side note, with Python 2.6, you could have also use the print function without parentheses like this:
print helped()
but this is not the case with Python 3.x
You simply need to execute the function. Currently, the helped() function is defined but not run in your code. Essentially, it's never used. Right now you use print (helped) and should be getting a error when instead, you should call the function
Change
print(helped)
to
print(helped())
So when I directly double click my Base64 encoder/decoder script, it opens and closes with an error, I luckily did print screen before it closed, and this is the error:
What does that even mean? The program runs perfectly in the IDLE, with no errors.
This is my code, take a look!
http://gyazo.com/69a31e3d63987bb44f4d8d69e01423bc.png
The error seems to be your use of input which is attempting to eval the string that you put in. This is the behavior of input on python2.x. You probably want to use raw_input. On python3.x, raw_input was renamed input and the previous input function was removed.
One trick that I tend to use in situations like these where I need to support python2.x and python3.x in the same script is to use raw_input everywhere and then at the top of your script do something like:
try:
raw_input # No error on python2.x
except NameError:
raw_input = input # python3.x
I tried to write my first python program and I already get an error message. In the textbook introduction to computer science using python i found the following code:
name = input('What is your name? ')
print('Hello', name)
print('Welcome to Python!')
I checked multiple times for errors and I'm quite sure i typed it exactly like the textbook states. I saved the program as MyFirstProgram.py and after that i ran the module (by pressing F5). If i understand correctly the program asks you to fill in a name. So i typed 'John'. But when i did, the following error occurs:
Traceback (most recent call last):
File "C:/Users/Wout/.ipython/MyFirstProgram.py", line 3, in <module>
name = input('What is your name? ')
File "<string>", line 1, in <module>
NameError: name 'John' is not defined
Why is 'John' not defined? Isn't it the purpose of the program to enter any name? Why do i have to define it? I followed the instructions to the letter...
Kind regards
input, in Python 2, evaluates the input as if it were a snippet of Python code. This is almost never what you want. Use raw_input instead.
By the way, you're writing your code as if it were Python 3, but you appear to be using a Python 2 interpreter. If you run your code with Python 3, it will work fine (input in Python 3 is the same as raw_input in Python 2).
You should use raw_input() instead of an input(), since you are on python-2.x:
name = raw_input('What is your name? ')
print('Hello', name)
print('Welcome to Python!')
prints:
What is your name? John
('Hello', 'John')
Welcome to Python!
You are following a textbook for Python 3 but using Python 2. In Python 2, must use raw_input and don't need brackets on print statements.
'John' will work with input (John won't work), however you should use raw_input() like the others said
To exit from Python command line, I have to type exit(). If I type exit, it says
Use exit() or Ctrl-Z plus Return to exit
Usually when you type exit, you would want to exit the program. Why does the interpreter give me the above error when it knows I am trying to exit the command line? Why doesn't it just exit? I know it doesn't matter and its a silly question but I am curious.
This works for me, best way to come out of python prompt.
exit()
In my python interpreter exit is actually a string and not a function -- 'Use Ctrl-D (i.e. EOF) to exit.'. You can check on your interpreter by entering type(exit)
In active python what is happening is that exit is a function. If you do not call the function it will print out the string representation of the object. This is the default behaviour for any object returned. It's just that the designers thought people might try to type exit to exit the interpreter, so they made the string representation of the exit function a helpful message. You can check this behaviour by typing str(exit) or even print exit.
When you type exit in the command line, it finds the variable with that name and calls __repr__ (or __str__) on it. Usually, you'd get a result like:
<function exit at 0x00B97FB0>
But they decided to redefine that function for the exit object to display a helpful message instead. Whether or not that's a stupid behavior or not, is a subjective question, but one possible reason why it doesn't "just exit" is:
Suppose you're looking at some code in a debugger, for instance, and one of the objects references the exit function. When the debugger tries to call __repr__ on that object to display that function to you, the program suddenly stops! That would be really unexpected, and the measures to counter that might complicate things further (for instance, even if you limit that behavior to the command line, what if you try to print some object that have exit as an attribute?)
With Anaconda 4.5+ and Python 3.6+ on Windows use
Ctrl+Z
or
exit()
In some cases, you might have to use
Ctrl+Break
If your computer doesn't have Break key then see here.
I recommend you exit the Python interpreter with Ctrl-D. This is the old ASCII code for end-of-file or end-of-transmission.
This message is the __str__ attribute of exit
look at these examples :
1
>>> print exit
Use exit() or Ctrl-D (i.e. EOF) to exit
2
>>> exit.__str__()
'Use exit() or Ctrl-D (i.e. EOF) to exit'
3
>>> getattr(exit, '__str__')()
'Use exit() or Ctrl-D (i.e. EOF) to exit'
Because the interpreter is not a shell where you provide commands, it's - well - an interpreter. The things that you give to it are Python code.
The syntax of Python is such that exit, by itself, cannot possibly be anything other than a name for an object. Simply referring to an object can't actually do anything (except what the read-eval-print loop normally does; i.e. display a string representation of the object).
You can fix that.
Link PYTHONSTARTUP to a python file with the following
# Make exit work as expected
type(exit).__repr__ = type(exit).__call__
How does this work?
The python command line is a read-evaluate-print-loop, that is when you type text it will read that text, evaluate it, and eventually print the result.
When you type exit() it evaluates to a callable object of type site.Quitter and calls its __call__ function which exits the system. When you type exit it evaluates to the same callable object, without calling it the object is printed which in turn calls __repr__ on the object.
We can take advantage of this by linking __repr__ to __call__ and thus get the expected behavior of exiting the system even when we type exit without parentheses.
To exit from Python terminal, simply just do:
exit()
Please pay attention it's a function which called as most user mix it with exit without calling, but new Pyhton terminal show a message...
or as a shortcut, press:
Ctrl + D
on your keyboard...
If you stuck in python command line and none of above solutions worked for you,
try exit(2)
"exit" is a valid variable name that can be used in your Python program. You wouldn't want to exit the interpreter when you're just trying to see the value of that variable.
This UX in python:
$ python
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
>>> ^D
File "<stdin>", line 1
♦
^
SyntaxError: invalid syntax
>>> exit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'exit' is not defined
>>> quit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'quit' is not defined
>>> exit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'exit' is not defined
>>> quit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'quit' is not defined
Two (related?) questions here.
I was trying to write a program to start an external process, and then simultaniouly read from stdout and write to stdin. Everything seemed to be working, however the process was not responding to the data sent to its stdin pipe. Do you know why this would be?(1)
This second question is solved now.
I wrote two testing scripts, the first was as such:
# recv.py
while True:
print(input())
The second was designed to call the other using Popen, the give it some arbitrary input:
# send.py
recv = subprocess.Popen(["python", "recv.py"], stdin=subprocess.PIPE)
recv.stdin.write(b"Hello\n")
recv.stdin.write(b"World.\n")
This is what I got when I ran it:
skyler#pro:testing$ python send.py
skyler#pro:testing$ Traceback (most recent call last):
File "recv.py", line 30, in <module>
main()
File "recv.py", line 26, in main
print(input())
File "<string>", line 1, in <module>
NameError: name 'Hello' is not defined
It looks like for whatever reason the result of input() is being treated like part of the line, instead of a string, indeed when I set a variable Hello in recv.py, it printed the contents of Hello. Why is this happening?(2)
I'm running python 3.1.2 on Mac OSX.
What you're seeing is the expected behaviour of Python 2.x's input() function, which takes a line from sys.stdin (like raw_input()) and then evaluates it as Python code. It's generally a bad idea to use input() in Python 2.x :) In Python 3.x, input() was removed and raw_input() was renamed to input(), which may be why you're confused about what it does.
You're not executing Python 3.x, even though you may have it installed. The python command is probably (hopefully!) still the system-installed Python 2.x. Try running it with python3 or python3.1 instead.
Make sure that you're actually running Python 3? That looks suspiciously like the Python 2.x input() behavior, where it would interpret the input as Python expressions (as opposed to raw_input() which became Python 3's input()).