从php执行python [英] Execute python from php

查看:54
本文介绍了从php执行python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个这样的课程:

Say you have a class like this:

class MyClass:
    def __init__(self, var1):
        self.var = var1
    ....

在python中,此类仅在分配值时才起作用:

This class, in python, works only when you assign a value:

x = MyClass("Hi")

所以基本上,我的问题是我是否可以从php发送变量以执行python类,并返回其输出(它是字符串)并继续执行我的php代码?

So basically, my question is whether I can send a variable from php to execute a python class, and return its output (it's string) and continue to execute my php code?

有什么建议吗?

解决方案

在php中:

$var = "something";
$result = exec("python fileName.py .$var")

在python中:

import sys

sys.argv[0] # this is the file name
sys.argv[1] # this is the variable passed from php

推荐答案

首先,创建一个包含要执行的python脚本的文件,包括(或加载)类和x = MyClass("Hi")

First of all, create a file containing the python-script you want to execute, including (or loading) the class and x = MyClass("Hi")

现在,使用以下行获取结果:

Now, use the following line to get the result:

$result = exec('python yourscript.py');

这篇关于从php执行python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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