从php执行python

Sha*_*kan 4 php python

假设你有这样一个类:

class MyClass:
    def __init__(self, var1):
        self.var = var1
    ....
Run Code Online (Sandbox Code Playgroud)

这个类在python中只在你赋值时起作用:

x = MyClass("Hi")
Run Code Online (Sandbox Code Playgroud)

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

有什么建议?

在PHP中:

$var = "something";
$result = exec("python fileName.py .$var")
Run Code Online (Sandbox Code Playgroud)

在python中:

import sys

sys.argv[0] # this is the file name
sys.argv[1] # this is the variable passed from php
Run Code Online (Sandbox Code Playgroud)

els*_*ooo 7

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

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

$result = exec('python yourscript.py');
Run Code Online (Sandbox Code Playgroud)