-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_runner.php
More file actions
110 lines (97 loc) · 2.78 KB
/
python_runner.php
File metadata and controls
110 lines (97 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
// v4.0
function pyConfig() {
$path = getcwd();
$path = $path."/.pyconfig.json";
if (file_exists($path)) {
$content = file_get_contents($path);
$jsonData = json_decode($content);
if (is_array($jsonData)) {
return $jsonData[0];
} elseif (is_object($jsonData) && $jsonData instanceof stdClass) {
return $path;
} else {
if (file_exists($path)) {
return $content;
} else {
return __DIR__ . "/pyconfig.json";
}
}
} else {
return __DIR__ . "/pyconfig.json";
}
}
$configFilePath = pyConfig();
function loadConfig($configFilePath)
{
if (!file_exists($configFilePath)) {
return false;
}
$configContent = file_get_contents($configFilePath);
return json_decode($configContent, true);
}
function runPython($pythonScriptPath)
{
global $configFilePath;
$config = loadConfig($configFilePath);
if (!$config) {
return "Error loading configuration file.";
}
$pythonPath = $config['pythonPath'];
$pythonVersion = $config['pythonVersion'];
$output = array();
$pythonScriptPath = script($pythonScriptPath);
exec("$pythonPath$pythonVersion $pythonScriptPath 2>&1", $output, $returnCode);
if ($returnCode === 0) {
return implode("\n", $output);
} else {
return "Error PythonAPI executing Python script. Return code: $returnCode\n" . implode("\n", $output);
}
}
function script($script)
{
$ending = ".py";
if (substr($script, -strlen($ending)) === $ending) {
return $script;
} else {
return $script . ".py";
}
}
class Python
{
private $data;
function __construct($data = null)
{
$this->data = $data;
}
public function getAlong(...$value)
{
global $configFilePath;
$config = loadConfig($configFilePath);
if (!$config) {
return "Error loading configuration file.";
}
$pythonPath = $config['pythonPath'];
$pythonVersion = $config['pythonVersion'];
$pythonScriptPath = script($this->data);
$command = "$pythonPath$pythonVersion $pythonScriptPath " . implode(' ', $value);
$output = shell_exec("$command 2>&1");
if ($output !== null) {
return trim($output);
} else {
return "Error executing Python script.";
}
}
function v()
{
global $configFilePath;
$config = loadConfig($configFilePath);
if (!$config) {
echo "Error loading configuration file.";
return;
}
$pythonPath = $config['pythonPath'];
$pythonVersion = $config['pythonVersion'];
echo shell_exec("$pythonPath$pythonVersion --version 2>&1");
}
}