Menu

[r5]: / trunk / python / python-test.php  Maximize  Restore  History

Download this file

67 lines (58 with data), 1.6 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
<?php
include_once "../lime/parse_engine.php";
include_once "python.class";
include_once "python-tokenizer.php";
/* Le definizioni lessicali per python
* http://docs.python.org/reference/lexical_analysis.html
* usare con cura...
*/
function tokenize($line) {
// Numbers are tokens, as are all other non-whitespace characters.
// Note: This isn't a particularly efficent tokenizer, but it gets the
// job done.
$out = array();
while (strlen($line)) {
$line = trim($line);
if (preg_match('/^[0-9]+(\.[0-9]*)?/', $line, $regs)) {
# It's a number
$out[] = $regs[0];
$line = substr($line, strlen($regs[0]));
} else if (preg_match('/^[A-Za-z]+/', $line, $regs)) {
# It's a variable name
$out[] = $regs[0];
$line = substr($line, strlen($regs[0]));
} else {
# It's some other character
$out[] = $line[0];
$line = substr($line, 1);
}
}
return $out;
}
$symbol_table = array();
function set_variable($v, $e) {
global $symbol_table;
$symbol_table[$v] = $e;
}
function get_variable($v) {
global $symbol_table;
return doubleval($symbol_table[$v]);
}
// Main function for run pyton code
function python_eval($pycode) {
global $parser;
$line = $pycode;
if (!strlen($line)) return;
try {
$parser->reset();
foreach(tokenize($line) as $t) {
if (is_numeric($t)) $parser->eat('num', doubleval($t));
else if (ctype_alpha($t)) $parser->eat('var', $t);
else $parser->eat("'$t'", null);
}
$parser->eat_eof();
} catch (parse_error $e) {
echo $e->getMessage(), "\n";
}
}
// Main parser object
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.