在PHP中调用Python [英] Calling Python in PHP

查看:124
本文介绍了在PHP中调用Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个最近编写的Python脚本,我使用命令行中的某些选项进行了调用.我现在想要一个非常薄的Web界面,以便在Mac上本地调用此脚本.

I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.

我不想在Mac上安装mod_python或mod_wsgi时遇到麻烦,所以我只想从PHP执行system()或popen()来调用Python脚本.

I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.

还有更好的主意吗?预先感谢!

Any better ideas? Thanks in advance!

推荐答案

根据您的工作, popen()可能是完美的.如果Python脚本没有输出,或者您希望Python脚本的输出直接进入浏览器,请使用system().如果要向Python脚本的标准输入中写入数据,或从php中的Python脚本的标准输出中读取数据,请使用popen(). popen()仅允许您读取或写入,而不能两者都读取.如果两者都需要,请检出 proc_open(),但要程序之间的双向通信需要小心以避免死锁,因为每个程序都在等待对方做某事.

Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.

如果要将用户提供的数据传递给Python脚本,则要注意的大事情是命令注入.如果您不小心,您的用户可以向您发送诸如; evilcommand;"之类的数据.并使您的程序按您的意愿执行任意命令.

If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.

escapeshellarg()

escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like

preg_replace('/[^a-zA-Z0-9]/', '', $str)

这篇关于在PHP中调用Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆