Python 脚本如何知道调用它的 PHP 文件的路径?

How can a Python script know the path of the PHP file calling it?

我正在使用 execfoo.php 执行一个 Python 脚本,我希望 Python 脚本知道 PHP 调用来自哪个目录从。在这个例子中,它应该是:/www/includes

# File tree
/script.py
/www/index.php
/www/includes/foo.php

foo.php

var_dump( exec( "/usr/bin/python /script.py" ) );

script.py

#!/usr/bin/env python

import os

print( os.getcwd() )

我发现在浏览器中直接调用 foo.php URL 时 os.getcwd() 效果很好。我得到了想要的结果:/www/includes

但是,当从不同目录中的另一个 PHP 文件调用 foo.php 时,它 不起作用 ,例如 /www/index.php

index.php

require_once '/www/includes/foo.php';

Python 脚本打印 /www,因为那是 index.php 所在的位置。

问题

foo.php 执行 Python 脚本时,我如何才能将其发送到 return /www/includes 而不管 foo.php 是如何调用的?我尝试了一些 traceback 方法但没有成功,因为我认为它只适用于跟踪错误。

您需要将您的工作目录更改为 foo.php 的目录,您应该可以使用 chdir:

chdir (__DIR__); # change working dir to current directory.

在foo.php