管道实现PHP与Python相互通信

 之前在公司做项目的时候碰到了一个解23个系数的回归方程的问题,当时只记得在大学的时候听数学老师讲过回归计算,后来也就还回去了。在网上也只能找到一个Python解回归方程的代码,而我用的主语言是PHP,对Python也只略懂些语法,所以只能想办法让PHP启一个Python进程再用进程间通信的方法来解决了。

 
看看管道文件的打开规则。
 
首先找到Linux下面的命名管道的创建方法。主要是用到一个命令
Usage: mkfifo [OPTION]... NAME...
Create named pipes (FIFOs) with the given NAMEs.
 
Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE set file permission bits to MODE, not a=rw - umask
  -Z, --context=CTX set the SELinux security context of each NAME to CTX
      --help display this help and exit
      --version output version information and exit
下面的英文不是很懂,-m的意思大致是设置这个管道文件的权限。(其实不用m参数直接创建管道文件后,用chmod来修改文件权限是一样的。)
# mkfifo -m 666 p1
# mkfifo -m 666 p2
我们建立了两个管道文件,p1用于 Python->PHP 的数据传输, p2用于PHP->Python的数据传输。
建立一个c.py文件,写入
  1 while True:
  2         fread = open("p2", "r")
  3         fwrite = open("p1", "w")
  4         str = fread.read(1024)
  5         fwrite.write(str)
  6         fwrite.close()
  7         fread.close()
这段Python的意思就是我从p2管道中读取数据, 再写入到p1管道中。
 
建立一个client.php文件。
<?php
 
function write($content)
{
 $fwrite = fopen("p2", "w");
 fwrite($fwrite, $content);
 fclose($fwrite);
}
 
function read()
{
 $fread = fopen("p1", "r");
 $content = fread($fread, 1024);
 fclose($fread);
 return $content;
}
 
write("abc");
$content = read();
 
for($i=0; $i<100; $i++)
{
 $num = rand().'';
 write($num);
 $num_read = read();
 assert($num === $num_read);
 
 echo $num_read, "\n";
}
这段php的作用就是从将随机内容写入p2管道,再从p1中读出来看看和之前写入的内容是否一样,如果不一样就报告异常。
 
先执行python c.py, 再执行php client.php。可以发现php正常执行完毕,没有报出异常,实验成功。


文章来自: 本站原创
Tags:
评论: 0 | 查看次数: 7298