Skip to main content

Changing CWD while using subprocess convenience methods

·132 words·1 min

Today I wanted to call a subprocess and get its output. Something like this:

arguments = ['git', 'log', '-1', '--pretty=format:"%ct"', self.path]
timestamp = check_output(arguments)

This worked great when I was staying in the source tree of a single git project. However, as soon as I asked git to get the log of a file outside the current source tree, it returned nothing. Clearly, I needed to change the CWD first.

In looking at the docs, I found a cwd argument on Popen, but not check_output. But this helpful post suggested that I could still pass the cwd argument becauseĀ che/code> and friends use Pop/code> underneath. And it works! Thanks to Shrikant for the tip. So the final code looks like this:

arguments = ['git', 'log', '-1', '--pretty=format:"%ct"', os.path.basename(self.path)]
timestamp = check_output(arguments, cwd=os.path.dirname(self.path))