php里面执行python,在php中执行python

2011-08-25

美国人Jon写了个PiP,Python in Php项目,可以实现在php中调用python。Jon 79年出生在新泽西州,毕业于罗切斯特理工,曾于2002年合写 Professional PHP4 Programming

示例:

1. Evaluating Python Code from PHP

Result

test 1 50 60.4

test 2.208 test

2. Python Object Instantiation

# module.py

class TestClass:

def __init__(self, foo):

self.foo = foo

def returnInt(self):

return 1113

def test(self, a, b = 'str'):

return "a = %d, b = %s" % (a, b)

def returnMe(self):

return self

def returnTuple(self):

return (1, "two", 3.0)

def returnList(self):

return [1, "two", 3.0]

def returnDict(self):

d = {}

d['one'] = 1

d['two'] = 2

d['three'] = 3

return d

def p(self, var):

print var

returnInt() . "n";

print $p->test(1, 'bar') . "n";

print $p->foo . "n";

$p->foo = 987;

print $p->foo . "n";

# $copy points to the same object

$copy = $p->returnMe();

print $copy->foo . "n";

$p->foo = 987;

print $copy->foo . "n";

?>

Result

1113

a = 1, b = bar

435

987

987

987

3. Type Conversion

returnTuple());

var_dump($p->returnList());

var_dump($p->returnDict());

$a = array('one' => 1, 2, 3);

$p->p($a);

class Test {

var $member = 'test';

}

$t = new Test();

$p->p($t);

?>

Result

array(3) {

[0]=>

int(1)

[1]=>

string(3) "two"

[2]=>

float(3)

}

array(3) {

[0]=>

int(1)

[1]=>

string(3) "two"

[2]=>

float(3)

}

array(3) {

["three"]=>

int(3)

["two"]=>

int(2)

["one"]=>

int(1)

}

{'1': 3, '0': 2, 'one': 1}

{'member': 'test'}

不过,如果不采用PiP这样的方式,也可以考虑用php的system()和popen(),proc_open()来调用。

如果要执行用户脚本,一定要注意安全。可以用escapeshellarg()和escapeshellcmd()或类似preg_replace(‘/[^a-zA-Z0-9]/’, ‘’, $str)去掉无关字符。

PiP官方页面:

http://www.csh.rit.edu/~jon/projects/pip/

如非注明转载, 均为原创. 本站遵循知识共享CC协议,转载请注明来源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值