executing Python script in PHP and exchanging data between the two

前端 未结 4 1012
挽巷
挽巷 2020-11-27 10:37

Is it possible to run a Python script within PHP and transferring variables from each other ?

I have a class that scraps websites for data in a certain global way. i

4条回答
  •  时光取名叫无心
    2020-11-27 11:15

    You can generally communicate between languages by using common language formats, and using stdin and stdout to communicate the data.

    Example with PHP/Python using a shell argument to send the initial data via 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:

    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)
    

提交回复
热议问题