Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke make from different directory with python script

Tags:

python

linux

I need to invoke make (build a makefile) in a directory different from the one I'm in, from inside a Python script. If I simply do:

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

I get the following: /bin/sh: ../dir1/dir2/dir3/make: No such file or directory

I've tried:

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

but the make command is ignored. I don't even get the "Nothing to build for" message.

I've also tried using "communicate" but without success. This is running on Red Hat Linux.

like image 630
jasper77 Avatar asked Jun 25 '10 21:06

jasper77


People also ask

How do I change directory in Python?

chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path. Parameters: path: A complete path of directory to be changed to new directory path.


2 Answers

I'd go with @Philipp's solution of using cwd, but as a side note you could also use the -C option to make:

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

-C dir, --directory=dir

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.

like image 108
John Kugelman Avatar answered Oct 28 '22 16:10

John Kugelman


Use the cwd argument, and use the list form of Popen:

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

Invoking the shell is almost never required and is likely to cause problems because of the additional complexity involved.

like image 22
Philipp Avatar answered Oct 28 '22 16:10

Philipp