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.
-
1What do you want to achieve can you please post some example code of what you have tried?Krk Rama Krishna– Krk Rama Krishna2020-09-27 08:11:38 +00:00Commented Sep 27, 2020 at 8:11
-
Does this answer your question? Python: Subprocess "call" function can't find pathwoblob– woblob2020-09-27 08:18:55 +00:00Commented Sep 27, 2020 at 8:18
2 Answers
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.)
3 Comments
make -C directory check should work too. That is, subprocess.run(['make', '-C', directory, 'check']) where we assume directory is a variable which contains the path to the directory.To add to tripleees excellent answer, you can solve this in 3 ways:
- Use subprocess'
cwdargument - Change dir before, using
os.chdir - Run the shell command to the exact dir you want, e.g.
ls /path/to/dirORcd /path/to/dir; ls, but note that some shell directives (e.g. &&, ;) cannot be used without addingshell=Trueto 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
5 Comments
; is among those, too. You really want to avoid shell=True if you can; see Actual meaning of shell=True in subprocessshell=True you normally pass in a single string and let the shell parse it, so e.g. ls /home/you/Desktop will work fine. Without shell=True you need to split this into a list yourself; ['ls', '/home/you/Desktop']ls bla bla. When adding shell True I leave it as it is, and when it's false, I add split()split doesn't work if your command has quoted strings which contain whitespace. There's shlex.split() which can handle this, and other complications; but again, perhaps your answer should spell these things out, or at least note that it's not entirely trivial to summarize the differences.