Python Forum

Full Version: Execute a Python script from a PHP web page
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a Python script (python-kasa). From the command line: kasa --host ipadd on
works fine. In my php web page I can "exec ('a program', $results);" and it I get the results. However when I try to run "exec ('kasa --host ip on', $results);" Nothing - doesn't turn the light on or off. I've tried by creating a bash script to run the kasa line - works - on, off, on, off - but calling the bash from my tst.php script it works. But http://localhost/tst.php - nothing, again. Google has been no help. Can you? Thanks in advance.
import pygame
import random
import os

# Initialize Pygame
pygame.init()

# Screen dimensions and game setup
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Godzilla RPG - Pokémon Style")

# Clock for controlling frame rate
clock = pygame.time.Clock()
FPS = 60

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# Load assets (placeholders for now)
ASSET_FOLDER = "assets"  # Folder for sprites and images
GODZILLA_SPRITE = os.path.join(ASSET_FOLDER, "godzilla_pixel.png")  # Replace with actual sprite
CITY_BACKGROUND = os.path.join(ASSET_FOLDER, "pixelated_city.png")  # Replace with pixelated map
ENEMY_SPRITE = os.path.join(ASSET_FOLDER, "enemy_pixel.png")  # Replace with enemy sprite

# Load sprites
godzilla_image = pygame.image.load(GODZILLA_SPRITE)
godzilla_image = pygame.transform.scale(godzilla_image, (64, 64))  # Resize sprite for pixel art
background_image = pygame.image.load(CITY_BACKGROUND)
background_image = pygame.transform.scale(background_image, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))
enemy_image = pygame.image.load(ENEMY_SPRITE)
enemy_image = pygame.transform.scale(enemy_image, (48, 48))  # Resize enemy sprite

# Player settings
player_x, player_y = 100, SCREEN_HEIGHT // 2  # Start position
player_speed = 4  # Movement speed

# Enemy settings
enemies = [pygame.Rect(random.randint(300, 1500), random.randint(0, SCREEN_HEIGHT - 50), 48, 48) for _ in range(5)]

# Game state variables
player_health = 100
player_max_health = 100
enemy_health = 50
enemy_max_health = 50
combat_mode = False
current_enemy = None
scroll_x = 0

# Combat actions
actions = ["Atomic Breath", "Tail Swipe", "Defend"]
selected_action = 0

# Fonts
font = pygame.font.Font(None, 36)

# Helper function: Render health bars
def render_health_bar(x, y, health, max_health, color):
    """Renders a health bar."""
    pygame.draw.rect(screen, BLACK, (x, y, 104, 14))  # Background
    pygame.draw.rect(screen, color, (x + 2, y + 2, (health / max_health) * 100, 10))  # Health bar

# Main game loop
running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # Check for game exit
            running = False
        if event.type == pygame.KEYDOWN and combat_mode:
            if event.key == pygame.K_UP:
                selected_action = (selected_action - 1) % len(actions)
            elif event.key == pygame.K_DOWN:
                selected_action = (selected_action + 1) % len(actions)
            elif event.key == pygame.K_RETURN:  # Execute the selected action
                if actions[selected_action] == "Atomic Breath":
                    enemy_health -= 20
                elif actions[selected_action] == "Tail Swipe":
                    enemy_health -= 15
                elif actions[selected_action] == "Defend":
                    player_health += 10
                    player_health = min(player_health, player_max_health)
                # Enemy counterattack
                player_health -= 10
                if player_health <= 0:
                    print("Game Over! Godzilla has been defeated.")
                    running = False
                if enemy_health <= 0:
                    print("Enemy defeated!")
                    combat_mode = False
                    enemies.remove(current_enemy)
                    current_enemy = None

    # Movement and exploration logic
    if not combat_mode:
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            player_y -= player_speed
        if keys[pygame.K_DOWN]:
            player_y += player_speed
        if keys[pygame.K_LEFT]:
            scroll_x += player_speed
        if keys[pygame.K_RIGHT]:
            scroll_x -= player_speed

        # Prevent player from leaving the screen vertically
        player_y = max(0, min(SCREEN_HEIGHT - godzilla_image.get_height(), player_y))
        scroll_x = max(-SCREEN_WIDTH, min(0, scroll_x))  # Restrict scrolling

        # Check for collisions with enemies
        for enemy in enemies:
            if godzilla_image.get_rect(topleft=(player_x - scroll_x, player_y)).colliderect(enemy):
                combat_mode = True
                current_enemy = enemy
                enemy_health = enemy_max_health
                break

    # Render the overworld
    screen.blit(background_image, (scroll_x, 0))  # Draw the scrolling background
    for enemy in enemies:
        screen.blit(enemy_image, (enemy.x + scroll_x, enemy.y))  # Draw enemies
    screen.blit(godzilla_image, (player_x, player_y))  # Draw Godzilla sprite

    # Render health bars
    render_health_bar(10, 10, player_health, player_max_health, GREEN)
    if combat_mode and current_enemy:
        render_health_bar(10, 30, enemy_health, enemy_max_health, RED)

    # Combat mode UI
    if combat_mode:
        pygame.draw.rect(screen, BLACK, (50, 400, 700, 180))  # Combat UI background
        for idx, action in enumerate(actions):
            color = GREEN if idx == selected_action else WHITE
            action_text = font.render(action, True, color)
            screen.blit(action_text, (100, 420 + idx * 40))

    pygame.display.flip()  # Update the display

    # Cap the frame rate
    clock.tick(FPS)

# Quit Pygame
pygame.quit()
I asked for some help with Python and the only reply I received was from a 14 year old gamer - Tristan
Unladen Swallow - hyping his simple game.
Have you tried using the library interface?

The problem with running your script might be that you did not specify a path to the script or that PHP doesn't have privilege to execute the script. Can you post the code for the script? That might generate more interest in solving your problem.
My solution: in the php web page - when a button is clicked - mysql insert into jobs2Bdone somevalue.
the last line in the page says "shell_exec (printf ('run.a.fake.it.script.bash) > /dev/null &)"; The bash script mysql selects from jobs2B, uses the value to execute a python file the deletes from jobs table - loops until table is empty. Web page runs - fast and the python scripts (up to 10 all run at the same time - in the background)