简体   繁体   English

来自php的Exec python

[英]Exec python from php

I'm trying to run a python script from php with 我正在尝试从php运行python脚本

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

My python file starts with #!/usr/bin/python and has exec rights. 我的python文件以#!/usr/bin/python开头,并具有执行权限。 For now I only have a print in there but it's not working( var_dump($res) gets me an empty array). 现在我只在那里打印,但是不工作( var_dump($res)给我一个空数组)。 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则应该可以正常工作:

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). 在这些情况下,您可能应该使用绝对路径(检查realpath以及chdir以及需要转义的所有参数)。

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. 我对文件中的Shebang的运行方式并不完全熟悉,但是我知道,如果从PHP调用它,将解释器包含在您运行的命令中会更好得多。

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. 如果是正常的Unix / Linux系统,则/home位于文件系统的根目录中。 . 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. 表示当前目录,因此除非您在运行PHP程序的目录中重新创建了/home文件系统,否则路径是错误的。 Also, unless your username is Desktop , you're missing a directory between /home/ and Desktop/ - it should be your username. 另外,除非您的用户名是Desktop ,否则您将缺少/home/Desktop/之间的目录-它应该是您的用户名。 The pwd command will never return a . pwd命令将永远不会返回. before the present working directory. 在当前工作目录之前。

For your second question, please refer to the docs on calling Python from the command line . 关于第二个问题,请参阅有关从命令行调用Python的文档。 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()"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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