使用python scrip从不同目录调用make

2024-05-14 17:01:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从一个Python脚本中调用make(构建makefile),这个目录与我所在的目录不同。如果我这么做:

build_ret = subprocess.Popen("../dir1/dir2/dir3/make",
                     shell = True, stdout = subprocess.PIPE)

我得到以下信息: /bin/sh:../dir1/dir2/dir3/make:没有这样的文件或目录

我试过:

build_ret = subprocess.Popen("(cd ../dir1/dir2/dir3/; make)",
                     shell = True, stdout = subprocess.PIPE)

但是make命令被忽略。我甚至没有收到“没什么可建”的信息。

我也试过用“交流”,但没有成功。这是在Red Hat Linux上运行的。


Tags: build目录脚本信息truemakestdoutshell
3条回答

我同意@Philipp使用cwd的解决方案,但作为补充说明,您也可以使用-C选项来:

make -C ../dir1/dir2/dir3/make

-C目录,--目录=目录

Change to directory dir before reading the makefiles or doing anything else. If multiple -C options are specified, each is interpreted relative to the previous one: -C / -C etc is equivalent to -C /etc. This is typically used with recursive invocations of make.

使用cwd参数,并使用Popen的列表形式:

subprocess.Popen(["make"], stdout=subprocess.PIPE, cwd="../dir1/dir2/dir3")

调用shell几乎从来都不是必需的,而且由于涉及到额外的复杂性,可能会导致问题。

尝试使用完整路径,可以通过调用

sys.argv[0]

为了找到路:

os.path.dirname(sys.argv[0])

您将在os.path module中找到相当多的路径操纵

相关问题 更多 >

    热门问题