简体   繁体   中英

Executing a python script via php

So Im trying to execute a python script from php using this code

exec('C:\Python27\python.exe    C:\WEBSITE_DATA\script.py');

or with double backspace...

exec('C:\\Python27\\python.exe    C:\\WEBSITE_DATA\\script.py');

the script is functional and generates a shape file when ran normally so the issue is not with the .py file.

I changed permissions to allow everyone full control from the python27 folder and the website data folder just to check if it were permissions issue

php log is absent of any errors so I can't chase don't any bugs or problems with code

I'm running IIS on windows server 2012 r2 is this my issue? Is what I'm trying to do even possible?

also if its possible can I exchange variables from php to python and then back?

That is very bad thing to do. That is very hacky and unsafe solution. Keep this in mind.

With this said, you should be looking for php system function that executes the command in console, not exec .

There are multiple ways to transfer variables from php script to Python. You can write data to MySQL database and then read them from Python script. You can pack all the variables in JSON using php zip and json_encode functions, save the JSON to file on disk, and then read it from the same location in Python script.

The simplest way though is to do this in your system call:

system("C:\Python27\python.exe /path/to/script.py $a $b $c")

This way the variables will be the arguments to Python script. There you ca just read them from sys.argv array like that:

import sys
a = sys.argv[1] # Note that the first argument is [1], not [0]
b = sys.argv[2]
...

To transfer values back to PHP script I suggest the same thing - saving them to JSON on the disk and then reading and parsing this JSON in PHP script after the execution of Python script is finished.

Now, although I told you how to do that, you absolutely should not. Much better way is to write a CGI script on Python that will process the request and do the work you initially written in Python.You can read more here - https://www.linux.com/blog/configuring-apache2-run-python-scripts

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