dhruvguptadg
dhruvguptadg

Reputation: 57

How to run shell commands in different directory using python subprocess command?

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

Answers (2)

CIsForCookies
CIsForCookies

Reputation: 12807

To add to tripleees excellent answer, you can solve this in 3 ways:

  1. Use subprocess' cwd argument
  2. Change dir before, using os.chdir
  3. Run the shell command to the exact dir you want, e.g. 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 call

PS 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

tripleee
tripleee

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

Related Questions