1

PHP code:

<?php
$data = array('1','4','67','34');

$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)));

$resultData = json_decode($result, true);

var_dump($resultData);


?>

Python Code:

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 = {'23','4'}

# Send it to stdout (to PHP)
print json.dumps(result)
5
  • Shouldn't you target a .exe file ? Commented Jul 2, 2013 at 12:19
  • 3
    Fyi, to pass larger amounts of data using stdin/stdout is much more appropriate than commandline arguments. Commented Jul 2, 2013 at 12:21
  • Can you narrow down where the failure is: PHP->Python, or Python->PHP? Commented Jul 2, 2013 at 12:21
  • @ThiefMaster can u tell me how to use stdin/stdout plus why it is giving NULL here is my question Commented Jul 2, 2013 at 12:23
  • the problem is that data in python script is coming out to be null.. can anyone fix that?? Commented Jul 2, 2013 at 13:19

2 Answers 2

1

There is incorrect data for json.dump() in Python

# Generate some data to send to PHP
result = {'23','4'}

So this give error, not json string

import sys, json

# Generate some data to send to PHP
result = {'23','4'}

# Send it to stdout (to PHP)
print json.dumps(result)

and PHP get NULL as $result from Python so you get NULL on screen - in browser

Use (for example):

# Generate some data to send to PHP
result = {'a':'23','b':'4'}

and json.dump() will work fine.

Sign up to request clarification or add additional context in comments.

2 Comments

@MichaelMallett In OP code I found only problem with json returned by Python. Python has problem with json.dump({'23','4'}) so it returns empty string, so PHP gives result NULL (on the screen - in browser). And OP asked for NULL problem. I tested it on computer with Linux Mint, Python 2.7.x, WWW server Apache 2.2.x, PHP 5.3.x. Did you found another explanation ?
are you using shell_exec() to run the python script in php? that will return null if there's a problem finding/executing the python script
1

Add 2>&1 (stdout & stderr) behind the command like so:

$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)) . ' 2>&1');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.