get the inverse of a php matrix from python file - php

PHP code:
<?php
$arr=array(array('1','2','3','4'),array('21','12','23','54'),array('10','23','35','41'),array('14','62','93','40'));
$result = shell_exec("C:/Python27/python 123.py ".json_encode($arr));
echo $result;
?>
python code:
import sys, json
arr=sys.argv[1]
print arr
A=np.matrix(arr)
print A
print ("<br/>")
M=A.I
print M
result = {'Name':'abc'}
print ("Sending data to PHP")
print (json.dumps(result))
The output given as inverse is not coming correct plus the A matrix is coming out to be of dimenesion 1x16 instead of 4x4 and the dimension of array arr is correct(4x4).How to debug it and get correct matrices A and M?

You seem not to be decoding the JSON within the Python script, whilst json_encode($arr) should be json_decode($arr) unless I'm wrong.

Related

What is the analogue of struct.pack() in php?

I have a variable id = 1615239032
In python i do
struct.pack('<i', id)
Result is
x\x97F`
In php i do
pack('i', $id)
But result is
x▒F`
How to get the same in php?
You already get the same as in Python. It gets corrupted when you try to display it.
If you convert the binary data to something else, for instance their hexadecimal represantions, you'll see that they are the same:
echo bin2hex("x\x97F`");
echo "<br>";
echo bin2hex(pack("i", 1615239032));
Result:
78974660
78974660

Pass JSON Data from PHP to Python Script

I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).
$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
The "escapeshellarg(json_encode($foods)))" function seems to hand off my array as the following to the Python script (I get this value if I 'echo' the function:
'["pizza","french fries"]'
Then inside the Python script:
import sys, json
data = json.loads(sys.argv[1])
foods = json.dumps(data)
print(foods)
This prints out the following to the browser:
["pizza", "french fries"]
This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem.
Had the same problem
Let me show you what I did
PHP :
base64_encode(json_encode($bodyData))
then
json_decode(shell_exec('python ' . base64_encode(json_encode($bodyData)) );
and in Python I have
import base64
and
content = json.loads(base64.b64decode(sys.argv[1]))
as Em L already mentioned :)
It works for me
Cheers!
You can base64 foods to string, then passed to the data to Python and decode it.For example:
import sys, base64
if len(sys.argv) > 1:
data = base64.b64decode(sys.argv[1])
foods = data.split(',')
print(foods)
If you have the json string: data = '["pizza","french fries"]' and json.loads(data) isn't working (which it should), then you can use: MyPythonList = eval(data). eval takes a string and converts it to a python object
Was having problems passing json from PHP to Python, my problem was with escaping the json string, which you are doing. But looks like you were decoding then re-encoding with "food"
From what I understand
Python json.dumps(data) == PHP json_encode(data)
Python json.loads(data) == PHP json_decode(data)
json.loads(data) -> String Data
json.load(data) -> File Data
json.dumps(data) -> String Data
json.dump(data) -> File Data
PHP:
$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
Python:
data = json.loads(sys.argv[1])
for v in data:
print(v)
ALSO
if you are passing key:value
PHP:
$foods = array("food1":"pizza", "food2":""french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
Python:
data = json.loads(sys.argv[1])
for(k,v) in content2.items():
print("k+" => "+v)
Python:
data = json.loads(sys.argv[1])
print(data['food1'])

Does python json output values have maximum length for json_decode (php) to handle?

I am trying to write a php code that takes coefficients from a html form, sends them to a python algorithm that returns a json object. That object is a list of player names, basically {"Ji" : "Firstname Lastname"} for i from 1 to 15.
The python code (interface.py) I have to create this json is :
import json
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]=joueur['nom']
out=json.dumps(output)
print(out)
best_team is a list of player dictionnaries with data on them. My player names don't involve any non ASCII characters or whatever.
My php code is the following :
$command = "python interface.py";
$command .= " $coeff1 $coeff2 $coeff3 $coeff4 $coeff5 $coeff6 $coeff7 $coeff8 $coeff9 $coeff10 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
$data = fread($pid, 256);
$data= json_decode($data) ;
echo $data->J1;
flush();
ob_flush();
echo "<script>window.scrollTo(0,99999);</script>";
usleep(100000);
}
pclose($pid);
I call the coefficients from the html and then send back the results via a js file.
But I just get the following error : Notice: Trying to get property of non-object.
Nothing wrong with the js file because if I try instead :
$string = '{"foo": "bar", "cool": "attributlong"}';
$result = json_decode($string);
echo $result ->cool;
It works.
Also if I have instead in my python file :
out={"foo":"bar","word":"longerthaneightcharacters"}
out=json.dumps(out)
print(out)
It works as well (replacing J1 by word in php code of course).
And funny enough, if i have in python:
output={}
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]="short"
output["J%s"%(i)]=str(output["J%s"%(i)])
out=json.dumps(output)
print(out)
It works, and if I replace "short" by "longerthaneightcharacters" it doesn't work anymore.
So basically my question is, why is there a maximum number of characters in my output loop and how can I bypass it ? Thanks, I am very confused.

How to decode Json in python and iterate

I am new in python,I am sending a php json encoded array to python
like this:
$myArray = array(1,5,8,6);
$jsonArray = json_encode($myArray);
exec("python ".$absPath."/myPythonFile.py $absPath $parm $jsonArray",$out);
Here is the python code:
from pydfs_lineup_optimizer import *
import sys
import json
optimizer = LineupOptimizer(FanDuelBasketballSettings)
optimizer.load_players_from_CSV("test_new.json")
try:
players_that_you_want = []
for number in sys.argv[3]:
print number
lineups = optimizer.optimize()
for l in lineups:
print(l)
except LineupOptimizerException as e:
print(e)
When I am trying to print number variable inside python file,This is how python returning:
[
1
,
5
,
8
,
6
]
and I want it like this:
1
5
8
6
Any Idea What I am doing wrong?
The argument is being sent in as a string, so you're not actually splitting it into the proper values with your loop. You can try stripping the square brackets and using split(',').
input = "[1,2,3,4]"
processed_input = input.strip('[]').split(',')
The above code will do the job.
This is what we need to do:
from pydfs_lineup_optimizer import *
import sys
import json
optimizer = LineupOptimizer(FanDuelBasketballSettings)
optimizer.load_players_from_CSV("test_new.json")
try:
players_that_you_want = []
for number in json.loads(sys.argv[3]):
print number
lineups = optimizer.optimize()
for l in lineups:
print(l)
except LineupOptimizerException as e:
print(e)

php to python inter-process communication with large data by json

my php code:
<?php
$data = array('as', 'df', 'gh');
$result=shell_exec("start test.py ".escapeshellarg(json_encode($data)));
?>
test.py code:
import sys
import json
try:
print json.loads(sys.argv[1])
except:
print "ERROR"
print
raw_input()
it's failing to try and showing ERROR.
while if change my python code to this:
import sys
try:
data=sys.argv[1]
except:
print "ERROR"
print data,
raw_input()
i'm getting the output as: [ as , df , gh ]
as i'm passing a json encoded data, i should be able to decode it with python's json.loads() method. but why it's not working?
don't know how it's working. but able to tune the program according to what i want.
php code:
<?php
$data = array('1'=>"as",'2'=>"df",'3'=>"gh");
$result=shell_exec("start test.py ".json_encode(json_encode($data)));
?>
test.py:
import sys
import json
try:
data=sys.argv[1]
except:
print "ERROR"
print data
dit=json.loads(data)
print dit
print dit['1']
raw_input()
and got the output as required:
{"1":"as","2":"df","3":"gh"}
{u'1': u'as', u'3': u'gh', u'2': u'df'}
as
someone having a good knowledge in these pls explain.
The problem is the following:
On Windows, escapeshellarg() removes percent signs, replaces double
quotes with spaces and adds double quotes around the string.
-> https://secure.php.net/manual/en/function.escapeshellarg.php
I'd recommend using addslashes(...)
exec("test.py " . addslashes(json_encode($json)) . " 2>&1", $output, $exit_code);

Categories