Reputation: 57
I am trying to execute a shell command, for e.g "ls" in a different directory from my python script. I am having issues changing the directory directly from the python code from subprocess.
Upvotes: 2
Views: 3843
Reputation: 12807
To add to tripleees excellent answer, you can solve this in 3 ways:
cwd
argumentos.chdir
ls /path/to/dir
OR cd /path/to/dir; ls
, but note that some shell directives (e.g. &&, ;) cannot be used without adding shell=True
to the method callPS as tripleee commented, using shell=True
is not encouraged and there are a lot of things that should be taken into consideration when using it
Upvotes: 2
Reputation: 189317
The subprocess
methods all accept a cwd
keyword argument.
import subprocess
d = subprocess.check_output(
['ls'], cwd='/home/you/Desktop')
Obviously, replace /home/you/Desktop
with the actual directory you want.
Most well-written shell commands will not require you to run them in any particular directory, but if that's what you want, this is how you do it.
If this doesn't solve your problem, please update your question to include the actual code which doesn't behave like you expect.
(Of course, a subprocess is a really poor way to get a directory listing, and ls
is a really poor way to get a directory listing if you really want to use a subprocess. Probably try os.listdir('/home/you/Desktop')
if that's what you actually want. But I'm guessing you are just providing ls
as an example of an external command.)
Upvotes: 2