import sys
sys.exit()

details from the sys module documentation:

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.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

Note that this is the 'nice' way to exit. @glyphtwistedmatrix below points out that if you want a 'hard exit', you can use os._exit(*errorcode*), 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 does kill the entire process, including all running threads, while sys.exit() (as it says in the docs) only exits if called from the main thread, with no other threads running.

Answer from pjz on Stack Overflow
Top answer
1 of 14
1852
import sys
sys.exit()

details from the sys module documentation:

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.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

Note that this is the 'nice' way to exit. @glyphtwistedmatrix below points out that if you want a 'hard exit', you can use os._exit(*errorcode*), 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 does kill the entire process, including all running threads, while sys.exit() (as it says in the docs) only exits if called from the main thread, with no other threads running.

2 of 14
530

A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.

Example:

#do stuff
if this == that:
  quit()
Top answer
1 of 1
2

IMHO the best way to do this is to have the running script periodically check for some flag that is set via the other script. One easy way to do that is to have the running script check for the existence of a file (stop-script, for example) which normally doesn't exist.

Then all you need to do in the script that is run when the Stop Button is pressed is to create (or touch) the file stop-script.

The running script should then delete the stop-script file just before it exits setting up for the next execution of the running script.

Here's what I envision in pseudo code (using python indentation for blocks):

sensor.py Script

while( TRUE )
  -- code to check sensor

  if exists '/path/to/stop-script'
     continue # exit while loop

  sleep(5)    # sleep for 5 seconds

print 'stop-script file detected'
delete file '/path/to/stop-script'
print 'stop-script file deleted - we will now exit'

button-2-pressed.py Script

execute_os_command("touch /path/to/stop-script")

Something like that.

Update: Answer to 2nd problem, namely web page hangs when running main script

Your second issue is that when in PHP you run exec('sudo python /var/www/SensorON.py'); , PHP will wait for the command to terminate, which in your case doesn't happen until later. You need to make this command run "asynchronously", see this for more detail, but effectively you need the following in your PHP web page:

if (isset($_POST['SensorON']))
{
    exec('sudo python /var/www/SensorON.py > /dev/null 2>/dev/null &');
}

if (isset($_POST['SensorOFF']))
{
    exec('sudo touch /var/www/SensorOFF.py');
}

By adding > /dev/null 2>/dev/null & to the command string redirects the output of the Python program to /dev/null (the bit bucket) and most importantly the final "&" character causes Python to run as a separate process and return is immediately returned to PHP allowing your web page to complete.

🌐
Cloudinary
cloudinary.com › home › how do you end a program in python?
How Do You End a Program in Python?
August 22, 2025 - Python provides several built-in ways to end your script. ... These are the most beginner-friendly. They’re essentially the same and work fine in interactive mode (like in the Python REPL or Jupyter Notebook): print("Program starting...") exit() print("This will not run.")Code language: PHP (php)
🌐
Kinsta®
kinsta.com › home › resource center › blog › web development languages › php vs python: a detailed comparison between the two languages
PHP vs Python: A Detailed Comparison Between the Two Languages
November 27, 2024 - Both WordPress and Python support MySQL. You will need a plugin that can initiate MySQL queries to your database, then display the output on your front-end. However, many wouldn’t want to go with these hassles. Hence, PHP, beyond a doubt, works great with WordPress and beats Python by a significant margin here.
🌐
TutorialsPoint
tutorialspoint.com › How-to-call-Python-file-from-within-PHP
How to call Python file from within PHP?
In PHP, we can execute Python scripts using built-in functions such as shell_exec(), exec() or popen() by enabling seamless integration between the two languages. Below are three methods to run a Python script from PHP with examples and explanations
🌐
Zend
zend.com › blog › php-vs-python
PHP vs. Python: Battle of the Backend Languages | Zend
Get an overview of PHP vs. Python from our expert, including comparisons on performance, security, benefits, and use cases for each back-end language.
🌐
PHP
php.net › manual › en › function.exit.php
PHP: exit - Manual
If you want to avoid calling exit() in FastCGI as per the comments below, but really, positively want to exit cleanly from nested function call or include, consider doing it the Python way: define an exception named `SystemExit', throw it instead of calling exit() and catch it in index.php with an empty handler to finish script execution cleanly. <?php // file: index.php class SystemExit extends Exception {} try { /* code code */ } catch (SystemExit $e) { /* do nothing */ } // end of file: index.php // some deeply nested function or .php file if (SOME_EXIT_CONDITION) throw new SystemExit(); // instead of exit() ?>
Find elsewhere
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › community › general discussion
php stop exec python code - Raspberry Pi Forums
Heater wrote:I would imagine that when PHP starts a program, like your Python script, it make the process ID of the started program available somehow. If you have the process ID then you can create more PHP that shells out to a bash command "kill -9 <id>". Where <id> is the actual process ID number.
🌐
Reddit
reddit.com › r/phphelp › executing python script from php and wait for it.
r/PHPhelp on Reddit: Executing Python Script from PHP and wait for it.
August 22, 2019 -

I was working on something that requires me to run a Python script with some arguments from PHP itself, and complete some task and print some output. The thing is, I tried shell_exec() and few more things mentioned in SO to run python script. But, the issue is that PHP doesn't seem to wait for my python script to complete. I need something that'll wait till the Python is done with the job. Can someone suggest me something?

EDIT : Typo in "shell_exec()" name.

UPDATE : After I re-looked at my script this morning.... seems like python can't open file. So, the PHP might not have permissions for that script. So, went ahead and gave it the perms. I added "www-data" group to that python file and changed python file's perms to 777. It still didn't work. But, the main issue right now is that Python script can't seem to be executed via apache2->Php.

Thanks everyone for all the help and hints. Appreciate it!

UPDATE 2 : I fixed the permission issue with "www-data" and it's working. THANKS EVERYONE!

🌐
Edureka Community
edureka.co › home › community › categories › python › how to terminate a python script
How to terminate a python script | Edureka Community
August 9, 2019 - In PHP there is a die() function that is used to display a message and exit the script. Is there something similar in Python?
Top answer
1 of 11
213

Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.

In PHP use shell_exec function:

Execute command via shell and return the complete output as a string.

It returns the output from the executed command or NULL if an error occurred or the command produces no output.

<?php 

$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;

?>

Into Python file test.py, verify this text in first line: (see shebang explain):

#!/usr/bin/env python

If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that's ok, but less flexible.

In Unix, an executable file that's meant to be interpreted can indicate what interpreter to use by having a #! at the start of the first line, followed by the interpreter (and any flags it may need).

If you're talking about other platforms, of course, this rule does not apply (but that "shebang line" does no harm, and will help if you ever copy that script to a platform with a Unix base, such as Linux, Mac, etc).

This applies when you run it in Unix by making it executable (chmod +x myscript.py) and then running it directly: ./myscript.py, rather than just python myscript.py

To make executable a file on unix-type platforms:

chmod +x myscript.py

Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl) and/or must be "executable". Also all commands into .py file must have correct privileges.

Taken from php manual:

Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.

2 of 11
30

I recommend using passthru and handling the output buffer directly:

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean(); 
Top answer
1 of 2
12

Will this work and I'd so how risky is it to future problems?

Yes it will work, and how risky it is depends on how good your implementation is. This is perfectly acceptable if done correctly. I have successfully integrated PHP and C, when PHP was simply too slow to do certain niche tasks in real time (IIRC, PHP is 7 times slower than its C counterpart).

The best implementation is to ignore the fact they are PHP/Python specifically, and just treat them as two separate languages.

Now, you need to pick some 'standard' way of interacting. HTTP is probably the easiest: everyone has a web server setup already so it's just a matter of putting the script online.

From here, you need to get away from the fact they are PHP/Python still and design your API without knowing that. For example, imagine you had a calculator:

<?php
print '<answer>' . ($_GET['one'] + $_GET['two']) . '</answer>';
?>

Then your API would be http://location/script.php?one=5&two=7. This is perfectly acceptable: the user of the API expects an answer within an <answer> tag (my example is a lazy mans XML, purely as a demonstration, but I think you should look into outputting JSON). This, is not:

<?php
print eval($_GET['expr']);
?>

Since your API would be http://location/script.php?expr=5+7. Even though it would result in the same answer (and, ignoring any major security flaws), the caller needs to know the implementation details of PHP (eval is a PHP function which will just evaluate its input as real PHP code). If they did 2^3, is that 2 xor 3 or 2 * 2 * 2 (2 to the power 3). This is a bad design: your inputs should be independent of the language your API is implemented in. On top of this, how do we distinguish between an error message and an answer? No magic "if the response is not a number", please.

Python side - you just need to make sure HTTP requests fail gracefully. If you can't connect to your script, perhaps try again, and if that fails, give up with a nice error message asking them to try again later. Don't just display them a Python stack trace.

You should also document your API as well as possible - this will save you a lot of time down the line. Say what each of the inputs should be, what ranges they should fall in, and give some good examples of how to use it.

API side - you should also try to fail quickly if something is wrong. If a variable is missing, incomplete, or invalid, print a message and exit as the first thing you do. Do not just run with the values, and then let them get back a PHP error message (remember, they should not know or care what language your API is implemented in), but should get a nice friendly You didn't give me a 'two' variable. What do you want me to add 'one' to?.

2 of 2
1

Jay's answer is correct that you can do this thing.

The normal way to describe this is that you'll be developing the python algorithm (function) into a "service" (standalone application) that your PHP app will "consume" (make calls to). This is a fine idea if the algorithm is complex enough that you want to think of it as its own program; sequestering your code into separate parts at various levels (separate objects, separate libraries, separate servers) is often a good idea, provided you have clean (defined) separation of concerns.

If you do go this route, HTTP(S) is a good option. The other easy synchronous option would be to use system calls, either to the python script directly or to a daemon wrapping the script. This may have performance advantages, and may be the fastest solution to write, but HTTPS is going to have big flexibility and security advantages.

If an asynchronous option will work I might suggest that. Your php app will leave a record of work to be done in some shared location (like the database), and your python app will be constantly polling* for work that needs to be done. Meanwhile, your php app will be checking for, and using the results of, finished work.
Asynchronous solutions like this are a little tricky to get right, but can be really nice once you have them.

(*If you're on a big cloud provider like AWS or Azure you may have better options than a poll.)

All that said, be mindful of the objections of your developers!
The decision to break one app into multiple apps shouldn't be taken lightly. There are a lot of reasons to split a system into simpler independent parts, but the fact that a contractor happened to write their piece in the "wrong" language isn't one of them.

🌐
Stackify
stackify.com › php-vs-python-which-should-you-choose-in-2019
PHP vs Python: Is There a Clear Choice in 2020? - Stackify
May 1, 2023 - PHP 7 introduced Composer, which is a fantastic tool, mostly feature complete, and (when paired with a tool like Packagist), you’ll find package management close to on-par with Python’s. Unfortunately, it’s still pretty young. At the end of the day, Python has a broader variety of mature packages, and their tools are a bit easier to install and use at this time.
🌐
PHP Freaks
forums.phpfreaks.com › php coding › php coding help
[SOLVED] PHP running Python script - not waiting for Python script to finish - PHP Coding Help - PHP Freaks
November 26, 2008 - Hey - Running these on a Linux server with PHP 5 and Python 2.5. My problem is this: I have a simple php form that executes a long (~3 minutes) Python script using the 'exec' function from php. The issue is that the browser, I think, 'times out' before the Python script is finished and therefore ...
🌐
W3Schools
w3schools.com › python › ref_string_endswith.asp
Python String endswith() Method
HTML Examples CSS Examples JavaScript Examples How To Examples SQL Examples Python Examples W3.CSS Examples Bootstrap Examples PHP Examples Java Examples XML Examples jQuery Examples · HTML Certificate CSS Certificate JavaScript Certificate Front End Certificate SQL Certificate Python Certificate PHP Certificate jQuery Certificate Java Certificate C++ Certificate C# Certificate XML Certificate
🌐
Orient Software
orientsoftware.com › blog › python-vs-php
Python Vs. PHP: The Good, the Bad, and the Difference
February 13, 2024 - PHP is the first programming language for web development - both front-end and back-end - while Python is more of a general-purpose language as it is used in a heap more use cases other than primarily web apps.
🌐
Delft Stack
delftstack.com › home › howto › python › python exit program
How to End Program in Python | Delft Stack
February 2, 2024 - End Python Program With the os.exit() Method · Conclusion · As in PHP, the die() command terminates the running script. Similarly, the Python scripts can be terminated by using different built-in functions like quit(), exit(), sys.exit(), ...