是否可以在PHP中运行Python脚本并互相传递变量?
我有一个类,可以以某种全局方式从网站上获取数据。我想让它更加具体化,并已经使用了几个特定于网站的Python脚本。
我正在寻找一种将这些脚本合并到我的类中的方法。
两者之间的安全可靠数据传输是否可能?如果可能,那么实现起来有多困难?
您通常可以使用通用语言格式,并使用 stdin
和 stdout
来传递数据,从而在语言之间进行通信。
使用PHP/Python的示例,通过shell参数以JSON格式发送初始数据
PHP:
// This is the data you want to pass to Python
$data = array('as', 'df', 'gh');
// Execute the python script with the JSON data
$result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));
// Decode the result
$resultData = json_decode($result, true);
// This will contain: array('status' => 'Yes!')
var_dump($resultData);
Python:
->Python:
import sys, json
# Load the data that PHP sent us
try:
data = json.loads(sys.argv[1])
except:
print "ERROR"
sys.exit(1)
# Generate some data to send to PHP
result = {'status': 'Yes!'}
# Send it to stdout (to PHP)
print json.dumps(result)
NULL
返回,可能是因为 escapeshellarg()
从编码的 JSON 中去除了双引号,导致 JSON 无效,因此导致 json.loads()
失败。请尝试在 PHP 中使用 base64_encode();
替代 escapeshellarg();
,并且在 Python 中使用 import base64
/base64.b64decode()
。此外,如果您的路径包含空格,请不要忘记用双引号将其括起来,例如 'python "path/that/has spaces/script.py" '
就像我的情况一样。祝顺利!:) - Brian我遇到了同样的问题,想要分享我的解决方案。(紧随Amadan的建议)
import subprocess
output = subprocess.check_output(["php", path-to-my-php-script, input1])
$blah = $argv[1];
if( isset($blah)){
// do stuff with $blah
}else{
throw new \Exception('No blah.');
}
$pythonoutput = `/usr/bin/env python pythoncode.py`;
使用JSON可能会使在两种语言中都易于生成和解析,因为它是标准的,并且两种语言都支持它(至少是非古代版本)。在Python中,
json.dumps(stuff)
然后在PHP中实现
$stuff = json_decode($pythonoutput);
对我来说,escapeshellarg(json_encode($data))
并没有给出一个完全格式化为json的字符串,而是像这样的东西:{ name : Carl , age : 23 }。
因此,在Python中,我需要使用.replace(' ', '"')
替换空格以获取一些真正的JSON,并能够将其转换为json.loads(sys.argv[1])
。
问题在于,当有人输入一个带有空格的名称,比如“Ca rl”时。