razeh razeh - 2 months ago 11
Python Question

How to set the current working directory in the Python sh module?

Is there a way to set the current working directory within a call to the Python sh module?

I'd like to be able to execute a command --- and only the command --- in a different directory than the one I'm currently in. Something along the lines of:

import sh
foo = sh.ls(_current_directory="/tmp")


woudl be nice.

Answer

Use the _cwd parameter to set the current working directory on a per-command basis:

import sh
print(sh.ls(_cwd='/tmp'))

This works for any command, not just sh.ls.