我在/ apps / tools / public / requestAudit中有一个名为requestAudit的C二进制可执行文件。该二进制文件在/apps/tools/sf/audits/audit.py下调用python脚本。现在我需要在我的audit.py脚本中找到二进制文件的绝对路径,即/ apps / tools / public / requestAudit。在二进制可执行文件所在的目录下创建日志文件是必需的。有什么办法可以通过编程获得它。请注意,即使我从任何地方调用该二进制文件,也应该始终获取二进制可执行文件的绝对路径。
谢谢
嗯,您要做的主要事情是在C脚本中获取当前的工作目录,然后您可以编写一些C代码以将结果与argv [0]结合起来以创建文件的完整路径并传递调用时将其作为命令行参数添加到您的python脚本中。另外,您可以将argv [0]和getcwd()的结果作为参数传递给Python脚本,这是我在下面所做的:
requestAudit.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char* argv[]) {
char* cwd = getcwd(NULL, 0);
char* command = "python audit.py ";
char* combine;
// I added 2 because 1 for the null terminator and 1 for the space
// between cwd and argv[0]
size_t len = strlen(command) + strlen(cwd) + strlen(argv[0]) + 2;
combine = malloc(sizeof(*combine)*len);
strncpy(combine, command, strlen(command) + 1);
strncat(combine, cwd, strlen(cwd) + 1);
strncat(combine, " ", 2);
strncat(combine, argv[0], strlen(argv[0]) + 1);
return system(combine);
}
audit.py
import sys
if __name__ == "__main__":
full_path = sys.argv[1] + sys.argv[2][1:]
print(full_path)