Running a Python script from PHP

后端 未结 9 2028
鱼传尺愫
鱼传尺愫 2020-11-22 00:57

I\'m trying to run a Python script from PHP using the following command:

exec(\'/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2\');

H

9条回答
  •  悲&欢浪女
    2020-11-22 01:16

    Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.

    In PHP use shell_exec function:

    Execute command via shell and return the complete output as a string.

    It returns the output from the executed command or NULL if an error occurred or the command produces no output.

    
    

    In Python file test.py, verify this text in first line: (see shebang explain):

    #!/usr/bin/env python
    

    Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl) and/or must be "executable". Also all commands into .py file must have correct privileges:

    Taken from php manual:

    Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.

    To make executable a file on unix-type platforms:

    chmod +x myscript.py
    

提交回复
热议问题