[Python] Running Python on a webserver using PHP

Discussão em 'Python' iniciado por Stack, Julho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using a PHP script to execute a Python script on a localhost XAMPP web server:

    <?php
    $python_path = 'C:\Users\alona\AppData\Local\Programs\Python\Python39\python.exe';
    $output = shell_exec($python_path . ' my_script.py');
    echo $output;
    ?>


    When the Python script contains simple output like print("Hi"), the PHP code executes the Python program and displays the output correctly.

    However, with a more complex Python code like this:

    import pytz
    from datetime import datetime

    city = input("What country do you live in? ")
    timezone = pytz.timezone(city)

    current_time = datetime.now(timezone)
    print("The time in your country is:", current_time.strftime("%H:%M:%S"))


    The PHP page only shows "What's your country?" without allowing the user to input their country or displaying the second output. The PHP script should function like a command line, but on a web page. So, just like running python my_script.py on my computer prompts: "What country do you live in?" and after inputting "Canada" it shows "The time in your country is: 09:52:06". The same functionality should be achieved with my PHP script.

    Continue reading...

Compartilhe esta Página