Exiting from python Command Line - python

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

Related

Python 3.3.2 doesn't allow me to use 'raise SystemExit'

name = input('name? ')
if len(name) == 0:
print('error.\n')
raise SystemExit
I receive an error when using python 3.3.2 (which is the version is school sadly) but it works fine on other versions e.g. 2.7.10 and 3.5
This is the error
Looking at the screenshot I can see Python prompt at the bottom:
This means the script is run in an interactive session (IDLE on Windows I guess). I haven't found any documentation, but other users have discovered that raising SystemExit in an interactive session does print the traceback.
So you should check and ensure that you are not launching the script in an interactive session.
Old answer:
Looks like it's a bug (or a particularity) in Python 3.3.2. According to this blog post:
If nothing catches the exception, then the python interpreter catches
it at the end, does not print a stack trace, and then calls exit.
I tried to raise SystemExit('asd') and the program just printed asd, so looks like it's true.
Either upgrade Python or try os._exit(1).
Not sure if this is what you want, but if you wanna exit use this:
import sys
name = raw_input('name? ')
if len(name) == 0:
print('error.\n')
sys.exit()
This exits the interpreter by raising SystemExit.
Why don't you use sys.exit()?
sys.exit([arg])
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
You probably have an handler set for excepthook:
https://docs.python.org/3/library/sys.html#sys.excepthook
You should be able to reset it by doing
sys.excepthook = sys.__excepthook__
Nevermind, the hook works correctly for BaseException, but weirdly enough not for SystemExit (which is a subclass of BaseException).
You're probably executing your program with
python3 -i whatever.py
This gives me the same behavior you witnessed:
dario#feynman ~> python3 -i /tmp/a.py
Traceback (most recent call last):
File "/tmp/a.py", line 11, in <module>
raise SystemExit()
SystemExit
>>>
Note the >>> at the end.
Just remove the -i flag, from whatever is executing your program
Alternatively, it's bad practice, but you can also use os._exit(1)

Emacs interactive Python mode delays evaluation [duplicate]

I'm using Python 3.3 and Emacs 23.4 on Windows 7. I'm getting some odd behaviour when using python-shell. If I type in a command that produces some sort of output I get the result immediately on the next line. If the Python statement I've entered causes an error however, no output is shown. When I type in the next Python statement and hit enter, the error message for the previous line will be displayed.
For example when I'm processing some command line arguments:
>>> args
Namespace(templatedir=None, xmldir=None)
>>> args.bobbins
>>> args.templatedir
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Namespace' object has no attribute 'bobbins'
>>>
The first statement prints out the value of the args variable.
The second statement should print out an error message but nothing is printed.
The third statement is correct but actually prints out the error from the second statement.
Does anybody have any idea what's wrong with my Python / Emacs setup?
This was a bug in Python, and was fixed.

why is python trying to open its help in my program?

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.

Emacs Python error delay

I'm using Python 3.3 and Emacs 23.4 on Windows 7. I'm getting some odd behaviour when using python-shell. If I type in a command that produces some sort of output I get the result immediately on the next line. If the Python statement I've entered causes an error however, no output is shown. When I type in the next Python statement and hit enter, the error message for the previous line will be displayed.
For example when I'm processing some command line arguments:
>>> args
Namespace(templatedir=None, xmldir=None)
>>> args.bobbins
>>> args.templatedir
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Namespace' object has no attribute 'bobbins'
>>>
The first statement prints out the value of the args variable.
The second statement should print out an error message but nothing is printed.
The third statement is correct but actually prints out the error from the second statement.
Does anybody have any idea what's wrong with my Python / Emacs setup?
This was a bug in Python, and was fixed.

Python strange behavior when called by Popen & writing to stdin

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

Categories