Skip to content

Instantly share code, notes, and snippets.

@urigoren
Last active February 7, 2021 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urigoren/835a1fba16cdd7a6223d09f933662c1f to your computer and use it in GitHub Desktop.
Save urigoren/835a1fba16cdd7a6223d09f933662c1f to your computer and use it in GitHub Desktop.
Call python via command line from php
Options +SymLinksIfOwnerMatch
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^((?!index\.php).+)$ /index.php?py=$1 [NC,L,QSA]
import sys, json
def main(args):
return args
if __name__=="__main__":
args={}
k=""
for a in sys.argv[1:]:
if a.startswith("-"):
k=a.strip("-")
else:
args[k]=a
try:
output = main(args)
except Exception as e:
output={"exception": type(e).__name__, "message": str(e)} if type(output)!=str:
output=json.dumps(output)
print(output)
<?php
if ((!array_key_exists('py',$_GET)) || (!file_exists($_GET['py'].'.py')))
{
header('Location: http://www.argmax.ml/');
die();
}
$py = $_GET['py'];
if ((strpos($py, ' ') !== false) || (strpos($py, '.') !== false)) {
header('Location: http://www.argmax.ml/');
die();
}
$args='';
foreach ($_REQUEST as $key => $value) {
if ($key!='py')
{
$value=escapeshellarg($value);
$key=escapeshellarg("--".$key);
$args.=" $key $value";
}
}
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: application/json');
echo exec("/bin/python $py.py $args");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment