Created
April 7, 2025 05:10
-
-
Save Muqsit/f93eab48cf943794361680b66488a257 to your computer and use it in GitHub Desktop.
PHP: Execute a python script with stdin data using proc_open() and print stdout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
function run_python(string $path, string $payload) : ?string{ | |
$process = proc_open(["/usr/bin/python3", $path], [ | |
0 => ["pipe", "r"], | |
1 => ["pipe", "w"], | |
2 => ["pipe", "w"], | |
], $pipes); | |
$process !== false || throw new InvalidArgumentException("Could not open process for python script: {$path}"); | |
try{ | |
fwrite($pipes[0], $payload); // write to stdin | |
fclose($pipes[0]); | |
$stdout = stream_get_contents($pipes[1]); | |
fclose($pipes[1]); | |
$stderr = stream_get_contents($pipes[2]); | |
fclose($pipes[2]); | |
$stderr === false || $stderr === "" || throw new InvalidArgumentException("An error occurred when running script: {$path}, {$stderr}"); | |
}finally{ | |
proc_close($process); | |
} | |
return $stdout !== false ? $stdout : null; | |
} | |
$path = "script.py"; | |
$payload = "hello world"; | |
$response = run_python($path, $payload); | |
echo $response; // You said: hello world\n |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data = input() | |
print("You said:", data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment