简体   繁体   中英

Exec python from php

I'm trying to run a python script from php with

$res = '';
exec('./home/Desktop/Scripts/fetch_matches.py', $res);

My python file starts with #!/usr/bin/python and has exec rights. For now I only have a print in there but it's not working( var_dump($res) gets me an empty array). What's missing?

Also, if I'll have different methods in that script, how would I call them?

If you change your exec to include /usr/bin/python this should work as expected:

exec('/usr/bin/python ./home/Desktop/Scripts/fetch_matches.py', $res);

In these circumstances you should probably use absolute paths (check realpath as well as chdir and any argument escaping you need to do).

I'm not completely familiar with how the shebang in files is run but I know if calling from PHP it's far better just to include the interpreter in the command you run.

You need to get rid of the . before the path. If it's a normal Unix/Linux system, /home is in the root of the filesystem. . means the current directory, so unless you've recreated the /home filesystem in the directory from which you're running the PHP program, the path is incorrect. Also, unless your username is Desktop , you're missing a directory between /home/ and Desktop/ - it should be your username. The pwd command will never return a . before the present working directory.

For your second question, please refer to the docs on calling Python from the command line . You can execute arbitrary code from the command line, which could be something along the lines of

python -c "from fetch_matches import Fetcher; Fetcher()"

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