Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing value from PHP script to Python script

Tags:

I looked at the other questions similar to this one, but can't figure this out still.

I have a basic php file that does this:

 ?php $item='example'; $tmp = exec("python testscriptphp.py .$item"); echo $tmp; ? 

While succesfully calls python that I have running on my webhostserver. Now in my python script i want something like this:

 item=$item print item 

Basically I'm asking how to pass variables from PHP to a python script and then back to php if necessary.

Thanks!

like image 447
stackVidec Avatar asked Feb 12 '11 08:02

stackVidec


People also ask

How can I pass variable from PHP to python?

let PHP store its data in a database, and the python script read from the same db (db should handle concurrency) let one process call the other process, passing data via stdin/stdout (circumvents file) use some other form of Inter Process Communication suitable for your platform.

Can PHP interact with python?

Yes it will work, and how risky it is depends on how good your implementation is. This is perfectly acceptable if done correctly. I have successfully integrated PHP and C, when PHP was simply too slow to do certain niche tasks in real time (IIRC, PHP is 7 times slower than its C counterpart).

Is it possible to pass data from PHP to JavaScript?

We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies.

How do you call a PHP function from python?

To call a Python file from within a PHP file, you need to call it using the shell_exec function.


2 Answers

Although netcoder pretty much gave you the answer in his comment, here's an example:

Python->PHP

example.py

import os os.system("/usr/bin/php example2.php whatastorymark") 

example2.php

<?php     echo $argv[1];  ?> 

PHP->Python

<?php     $item='example';     $tmp = exec("python testscriptphp.py .$item");     echo $tmp;  ?> 

testscriptphp.py

import sys print sys.argv[1] 

Here's how PHP's command line argument passing works: http://php.net/manual/en/reserved.variables.argv.php The same for Python: http://docs.python.org/library/sys.html#sys.argv

like image 190
Uku Loskit Avatar answered Sep 20 '22 17:09

Uku Loskit


write a php file example index.php:

<?PHP $sym = $_POST['symbols']; echo shell_exec("python test.py .$sym"); ?> 

$sym is a parameter we passining to test.py python file. then create a python example test.py:

import sys print(sys.argv[1]) 

I hope it help you.

like image 36
Integraty_beast Avatar answered Sep 18 '22 17:09

Integraty_beast