Python调用PHP的函数
jopen
11年前
应用需求:
在电子商务的web平台中有可能存在这样的需求,在月末进行分红账务结算,这样就需要在web服务器下写脚本定时执行数据库的操作,这里有很多种可选的方案,Python调
用PHP函数只是其中的一种处理方式。
Python端代码:
#!/usr/bin/python import subprocess method="prom_timing_exec" proc=subprocess.Popen(['php -f /var/www/html/vsdev/model/Keke_witkey_prom_timing_exec.php '+method],shell=True,stdout=subprocess.PIPE); response=proc.stdout.read(); print(response);
这里需要注意一点:参数是添加在url后面的,且需要用空格隔开。即使是调用某个函数,其函数名也是需要通过参数传递。
PHP端代码:
<?php /* * @ author: Houqd * @ date : 2013-09-06 * @ des : This file contains all function that need timing execute in Python script. **/ $method = $argv[1]; class db_op { public $_conn; public $_select; public $_dbname; public $_tablename; public $_sql; public $_where; function db_op($dbname) { $this->_dbname = $dbname; $this->_tablename = "keke_witkey_prom_event"; } function db_connect() { $this->_conn = @mysql_connect("192.168.1.50","root","dell_456"); } function db_select() { $this->_select = @mysql_select_db($this->_dbname , $this->_conn); } function setWhere($where) { $this->_where = $where; } function execute($sql) { $result = mysql_query($sql); if($result){ while($row = mysql_fetch_array($result)) { $return[] = $row; } return $return; } return false ; } function query() { if(!$this->_conn){ $this->db_connect(); } if(!$this->_select){ $this->db_select(); } if(isset($this->_where)){ $sql = "select * from %s.".$this->_tablename." where ".$this->_where; }else{ $sql = "select * from %s.".$this->_tablename; } return $this->execute(sprintf($sql , $this->_dbname)); } } function prom_timing_exec() { $db_op = new db_op("keke_witkey"); $exec_result = $db_op->query(); print_r($exec_result); } if(isset($method) && $method != ""){ return $method(); }else{ echo "No function to call."; } ?>
注意:这里在PHP中接收传过来的参数是用:$argv变量来接收的,$argv[0]是php文件名,$argv[1]是第一个参数,$argv[2]是第二个参数....
来自:http://blog.csdn.net/houqd2012/article/details/11266319