Skip to content

Instantly share code, notes, and snippets.

@Muqsit
Created April 7, 2025 05:10
Show Gist options
  • Save Muqsit/f93eab48cf943794361680b66488a257 to your computer and use it in GitHub Desktop.
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
<?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
data = input()
print("You said:", data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment