<p>How do I exit a script early, like the <code>die()</code> command in PHP?</p>

[{'answer_id': 73673, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 12, 'selected': True, 'text': '<pre><code>import sys\nsys.exit()\n</code></pre>\n<p>details from the <a href="https://docs.python.org/2/library/sys.html#sys.exit" rel="noreferrer"><code>sys</code> module documentation</a>:</p>\n<blockquote>\n<p><code>sys.<strong>exit</strong>([<em>arg</em>])</code></p>\n<p>Exit from Python. This is implemented by raising the\n<a href="https://docs.python.org/2/library/exceptions.html#SystemExit" rel="noreferrer" title="SystemExit"><code>SystemExit</code></a> exception, so cleanup actions specified by finally clauses\nof <a href="https://docs.python.org/2/reference/compound_stmts.html#try" rel="noreferrer" title="try"><code>try</code></a> statements are honored, and it is possible to intercept the\nexit attempt at an outer level.</p>\n<p>The optional argument <em>arg</em> can be an integer giving the exit status\n(defaulting to zero), or another type of object. If it is an integer,\nzero is considered “successful termination” and any nonzero value is\nconsidered “abnormal termination” by shells and the like. Most systems\nrequire it to be in the range 0-127, and produce undefined results\notherwise. Some systems have a convention for assigning specific\nmeanings to specific exit codes, but these are generally\nunderdeveloped; Unix programs generally use 2 for command line syntax\nerrors and 1 for all other kind of errors. If another type of object\nis passed, None is equivalent to passing zero, and any other object is\nprinted to <a href="https://docs.python.org/2/library/sys.html#sys.stderr" rel="noreferrer" title="sys.stderr"><code>stderr</code></a> and results in an exit code of 1. In particular,\n<code>sys.exit(&quot;some error message&quot;)</code> is a quick way to exit a program when\nan error occurs.</p>\n<p>Since <a href="https://docs.python.org/2/library/constants.html#exit" rel="noreferrer" title="exit"><code>exit()</code></a> ultimately “only” raises an exception, it will only exit\nthe process when called from the main thread, and the exception is not\nintercepted.</p>\n</blockquote>\n<p>Note that this is the \'nice\' way to exit.  @<a href="https://stackoverflow.com/questions/73663/terminating-a-python-script#76374">glyphtwistedmatrix</a> below points out that if you want a \'hard exit\', you can use <code>os._exit(*errorcode*)</code>, though it\'s likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn\'t let the interpreter do any cleanup before the process dies.  On the other hand, it <em>does</em> kill the entire process, including all running threads, while <code>sys.exit()</code> (as it says in the docs) only exits if called from the main thread, with no other threads running.</p>\n'}, {'answer_id': 73680, 'author': 'Vhaerun', 'author_id': 11234, 'author_profile': 'https://Stackoverflow.com/users/11234', 'pm_score': 7, 'selected': False, 'text': '<p>Another way is:</p>\n\n<pre><code>raise SystemExit\n</code></pre>\n'}, {'answer_id': 73695, 'author': 'cleg', 'author_id': 29503, 'author_profile': 'https://Stackoverflow.com/users/29503', 'pm_score': 5, 'selected': False, 'text': '<pre><code>from sys import exit\nexit()\n</code></pre>\n\n<p>As a parameter you can pass an exit code, which will be returned to OS. Default is 0.</p>\n'}, {'answer_id': 76374, 'author': 'Glyph', 'author_id': 13564, 'author_profile': 'https://Stackoverflow.com/users/13564', 'pm_score': 6, 'selected': False, 'text': '<p>While you should generally prefer <code>sys.exit</code> because it is more "friendly" to other code, all it actually does is raise an exception.</p>\n\n<p>If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch <code>SystemExit</code>, there is another function - <code>os._exit</code> - which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the "atexit" module are not executed.</p>\n'}, {'answer_id': 14836329, 'author': 'j.m.g.r', 'author_id': 2065348, 'author_profile': 'https://Stackoverflow.com/users/2065348', 'pm_score': 9, 'selected': False, 'text': '<p>A simple way to terminate a Python script early is to use the built-in <code>quit()</code> function. There is no need to import any library, and it is efficient and simple.</p>\n\n<p>Example:</p>\n\n<pre><code>#do stuff\nif this == that:\n  quit()\n</code></pre>\n'}, {'answer_id': 16150238, 'author': 'Space cowboy', 'author_id': 1897240, 'author_profile': 'https://Stackoverflow.com/users/1897240', 'pm_score': 7, 'selected': False, 'text': '<p>You can also use simply <code>exit()</code>.</p>\n\n<p>Keep in mind that <code>sys.exit()</code>, <code>exit()</code>, <code>quit()</code>, and <code>os._exit(0)</code> <strong>kill</strong> the Python interpreter. Therefore, if it appears in a script called from another script by <code>execfile()</code>, it stops execution of both scripts. </p>\n\n<p>See "<a href="https://stackoverflow.com/a/1028632/1897240">Stop execution of a script called with execfile</a>" to avoid this.</p>\n'}, {'answer_id': 22504027, 'author': 'Floggedhorse', 'author_id': 2428737, 'author_profile': 'https://Stackoverflow.com/users/2428737', 'pm_score': 5, 'selected': False, 'text': '<p>I\'m a total novice but surely this is cleaner and more controlled</p>\n\n<pre><code>def main():\n    try:\n        Answer = 1/0\n        print  Answer\n    except:\n        print \'Program terminated\'\n        return\n    print \'You wont see this\'\n\nif __name__ == \'__main__\': \n    main()\n</code></pre>\n\n<p>...</p>\n\n<blockquote>\n  <p>Program terminated</p>\n</blockquote>\n\n<p>than</p>\n\n<pre><code>import sys\ndef main():\n    try:\n        Answer = 1/0\n        print  Answer\n    except:\n        print \'Program terminated\'\n        sys.exit()\n    print \'You wont see this\'\n\nif __name__ == \'__main__\': \n    main()\n</code></pre>\n\n<p>...</p>\n\n<blockquote>\n  <blockquote>\n    <p>Program terminated Traceback (most recent call last):   File "Z:\\Directory\\testdieprogram.py", line 12, in \n        main()   File "Z:\\Directory\\testdieprogram.py", line 8, in main\n        sys.exit() SystemExit</p>\n  </blockquote>\n</blockquote>\n\n<p>Edit</p>\n\n<p>The point being that the program ends smoothly and peacefully, rather than <strong>"I\'VE STOPPED !!!!"</strong></p>\n'}, {'answer_id': 40525942, 'author': 'eaydin', 'author_id': 1278994, 'author_profile': 'https://Stackoverflow.com/users/1278994', 'pm_score': 6, 'selected': False, 'text': '<p>I\'ve just found out that when writing a multithreadded app, <code>raise SystemExit</code> and <code>sys.exit()</code> both kills only the running thread. On the other hand, <code>os._exit()</code> exits the whole process. This was discussed in "<a href="https://stackoverflow.com/questions/905189/why-does-sys-exit-not-exit-when-called-inside-a-thread-in-python/5120178#5120178">Why does sys.exit() not exit when called inside a thread in Python?</a>".</p>\n\n<p>The example below has 2 threads. Kenny and Cartman. Cartman is supposed to live forever, but Kenny is called recursively and should die after 3 seconds. (recursive calling is not the best way, but I had other reasons)</p>\n\n<p>If we also want Cartman to die when Kenny dies, Kenny should go away with <code>os._exit</code>, otherwise, only Kenny will die and Cartman will live forever.</p>\n\n<pre><code>import threading\nimport time\nimport sys\nimport os\n\ndef kenny(num=0):\n    if num &gt; 3:\n        # print("Kenny dies now...")\n        # raise SystemExit #Kenny will die, but Cartman will live forever\n        # sys.exit(1) #Same as above\n\n        print("Kenny dies and also kills Cartman!")\n        os._exit(1)\n    while True:\n        print("Kenny lives: {0}".format(num))\n        time.sleep(1)\n        num += 1\n        kenny(num)\n\ndef cartman():\n    i = 0\n    while True:\n        print("Cartman lives: {0}".format(i))\n        i += 1\n        time.sleep(1)\n\nif __name__ == \'__main__\':\n    daemon_kenny = threading.Thread(name=\'kenny\', target=kenny)\n    daemon_cartman = threading.Thread(name=\'cartman\', target=cartman)\n    daemon_kenny.setDaemon(True)\n    daemon_cartman.setDaemon(True)\n\n    daemon_kenny.start()\n    daemon_cartman.start()\n    daemon_kenny.join()\n    daemon_cartman.join()\n</code></pre>\n'}, {'answer_id': 41350119, 'author': 'David C.', 'author_id': 6036809, 'author_profile': 'https://Stackoverflow.com/users/6036809', 'pm_score': 4, 'selected': False, 'text': '<p>In Python 3.5, I tried to incorporate similar code without use of modules (e.g. sys, Biopy) other than what\'s built-in to stop the script and print an error message to my users. Here\'s my example:</p>\n\n<pre><code>## My example:\nif "ATG" in my_DNA: \n    ## &lt;Do something &amp; proceed...&gt;\nelse: \n    print("Start codon is missing! Check your DNA sequence!")\n    exit() ## as most folks said above\n</code></pre>\n\n<p>Later on, I found it is more succinct to just throw an error:</p>\n\n<pre><code>## My example revised:\nif "ATG" in my_DNA: \n    ## &lt;Do something &amp; proceed...&gt;\nelse: \n    raise ValueError("Start codon is missing! Check your DNA sequence!")\n</code></pre>\n'}, {'answer_id': 60805367, 'author': 'Matthew', 'author_id': 12898298, 'author_profile': 'https://Stackoverflow.com/users/12898298', 'pm_score': 2, 'selected': False, 'text': "<p>My two cents.</p>\n\n<p>Python 3.8.1, Windows 10, 64-bit.</p>\n\n<p><code>sys.exit()</code> does not work directly for me.</p>\n\n<p>I have several nexted loops.</p>\n\n<p>First I declare a boolean variable, which I call <code>immediateExit</code>.</p>\n\n<p>So, in the beginning of the program code I write:</p>\n\n<pre><code>immediateExit = False\n</code></pre>\n\n<p>Then, starting from the most inner (nested) loop exception, I write:</p>\n\n<pre><code>            immediateExit = True\n            sys.exit('CSV file corrupted 0.')\n</code></pre>\n\n<p>Then I go into the immediate continuation of the outer loop, and before anything else being executed by the code, I write:</p>\n\n<pre><code>    if immediateExit:\n        sys.exit('CSV file corrupted 1.')\n</code></pre>\n\n<p>Depending on the complexity, sometimes the above statement needs to be repeated also in except sections, etc.</p>\n\n<pre><code>    if immediateExit:\n        sys.exit('CSV file corrupted 1.5.')\n</code></pre>\n\n<p>The custom message is for my personal debugging, as well, as the numbers are for the same purpose - to see where the script really exits. </p>\n\n<pre><code>'CSV file corrupted 1.5.'\n</code></pre>\n\n<p>In my particular case I am processing a CSV file, which I do not want the software to touch, if the software detects it is corrupted. Therefore for me it is very important to exit the whole Python script immediately after detecting the possible corruption.</p>\n\n<p>And following the gradual sys.exit-ing from all the loops I manage to do it.</p>\n\n<p>Full code: (some changes were needed because it is proprietory code for internal tasks):</p>\n\n<pre><code>immediateExit = False\nstart_date = '1994.01.01'\nend_date = '1994.01.04'\nresumedDate = end_date\n\n\nend_date_in_working_days = False\nwhile not end_date_in_working_days:\n    try:\n        end_day_position = working_days.index(end_date)\n\n        end_date_in_working_days = True\n    except ValueError: # try statement from end_date in workdays check\n        print(current_date_and_time())\n        end_date = input('&gt;&gt; {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))\n        print('New end date: ', end_date, '\\n')\n        continue\n\n\n    csv_filename = 'test.csv'\n    csv_headers = 'date,rate,brand\\n' # not real headers, this is just for example\n    try:\n        with open(csv_filename, 'r') as file:\n            print('***\\nOld file {} found. Resuming the file by re-processing the last date lines.\\nThey shall be deleted and re-processed.\\n***\\n'.format(csv_filename))\n            last_line = file.readlines()[-1]\n            start_date = last_line.split(',')[0] # assigning the start date to be the last like date.\n            resumedDate = start_date\n\n            if last_line == csv_headers:\n                pass\n            elif start_date not in working_days:\n                print('***\\n\\n{} file might be corrupted. Erase or edit the file to continue.\\n***'.format(csv_filename))\n                immediateExit = True\n                sys.exit('CSV file corrupted 0.')\n            else:\n                start_date = last_line.split(',')[0] # assigning the start date to be the last like date.\n                print('\\nLast date:', start_date)\n                file.seek(0) # setting the cursor at the beginnning of the file\n                lines = file.readlines() # reading the file contents into a list\n                count = 0 # nr. of lines with last date\n                for line in lines: #cycling through the lines of the file\n                    if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.\n                        count = count + 1\n        if immediateExit:\n            sys.exit('CSV file corrupted 1.')\n        for iter in range(count): # removing the lines with last date\n            lines.pop()\n        print('\\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))\n\n\n\n        if immediateExit:\n            sys.exit('CSV file corrupted 1.2.')\n        with open(csv_filename, 'w') as file:\n            print('\\nFile', csv_filename, 'open for writing')\n            file.writelines(lines)\n\n            print('\\nRemoving', count, 'lines from', csv_filename)\n\n        fileExists = True\n\n    except:\n        if immediateExit:\n            sys.exit('CSV file corrupted 1.5.')\n        with open(csv_filename, 'w') as file:\n            file.write(csv_headers)\n            fileExists = False\n    if immediateExit:\n        sys.exit('CSV file corrupted 2.')\n\n</code></pre>\n"}, {'answer_id': 70811775, 'author': 'Artyom Vancyan', 'author_id': 12755187, 'author_profile': 'https://Stackoverflow.com/users/12755187', 'pm_score': 4, 'selected': False, 'text': "<h2>Problem</h2>\n<p>In my practice, there was even a case when it was necessary to kill an entire multiprocessor application from one of those processes.</p>\n<p>The following functions work well if your application uses the only main process. But no one of the following functions didn't work in my case as the application had many other alive processes.</p>\n<ul>\n<li><code>quit()</code></li>\n<li><code>exit(0)</code></li>\n<li><code>os._exit(0)</code></li>\n<li><code>sys.exit(0)</code></li>\n<li><code>os.kill(os.getppid(), 9)</code> - where <code>os.getppid()</code> is the <strong>pid</strong> of parent process</li>\n</ul>\n<p>The last one killed the main process and itself but the rest processes were still alive.</p>\n<h2>Solution</h2>\n<p>I had to kill it by external command and finally found the solution using <code>pkill</code>.</p>\n<pre><code>import os\n\n# This can be called even in process worker and will kill\n# whole application included correlated processes as well\nos.system(f&quot;pkill -f {os.path.basename(__file__)}&quot;)\n</code></pre>\n"}, {'answer_id': 70824754, 'author': 'ChanceMeteor515', 'author_id': 18007782, 'author_profile': 'https://Stackoverflow.com/users/18007782', 'pm_score': 1, 'selected': False, 'text': '<p>Just put at the end of your code <code>quit()</code> and that should close a python script.</p>\n'}, {'answer_id': 72902963, 'author': 'jimh', 'author_id': 3705490, 'author_profile': 'https://Stackoverflow.com/users/3705490', 'pm_score': 2, 'selected': False, 'text': '<p>In Python 3.9, you can also use: <code>raise SystemExit(&quot;Because I said so&quot;)</code>.</p>\n'}]
['https://Stackoverflow.com/questions/73663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384652/']