简体   繁体   中英

Executing python commands from php script

I have installed SymPi in the server and from the command line, I am able to execute the following.

python ./sympy-0.7.5/bin/isympy

(this will open a console where I can type mathematical expressions. then the following expression)

1 + 2

(will give 3 as output)

My aim is to do the same from php using shell_exec . I have written a php file as given below, but is not working.

$command = escapeshellcmd('python ./sympy-0.7.5/bin/isympy');
shell_exec($command);
$output = shell_exec('1 + 2');

Can anybody help me to figure out why this is not working?

Please note that the following script works fine which just execute a python script and retrieve the output.

$command = escapeshellcmd('python C:\PythonPrograms\test3.py');
$output = shell_exec($command);
echo $output;

Each time you run shell_exec, it opens a completely new instance of the shell.

Edit:

You can pass a command for python to execute like this:

$expression = '1 + 2';
$cmd = 'python -c \'print "%f" % (' . $expression . ')\'';
$output = shell_exec($cmd);

This, admittedly is not using sympy, but for simple mathmatical expressions you may not need to. If you do, you would just need to import the library in the same command, like this: python -c 'import sympy; print "%f" % sympy.sqrt(3)' python -c 'import sympy; print "%f" % sympy.sqrt(3)'

My guess is that the working directory (cwd) of shell_exec is different from the one you're in when you execute it manually.

Your working example specifies a hard path that will work from anywhere. Whereas your not-working example specifies a relative path ( ./ is the cwd).

Convert your call to isympy to give its full path on disk. Or figure out how to set the cwd of shell_exec .

(If this doesn't solve it, say more than "is not working." What happens? An error? What is the full text of the error?)

I could manage the desired result in a different way.

  1. Created a python script which accepts the expression as the command line argument , execute and display the output.

  2. Call this script from php by passing the expression as the command line argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM