Reputation: 2147
I simply want to execute some subprocesses form Python. As an example, I just change the directory with cd but it does not seem to work:
import subprocess
from pathlib import Path
subprocess.run('cd ' + str(Path.cwd()) + '/h5_to_pb/', capture_output=True)
...
Throws error :
FileNotFoundError: [Errno 2] No such file or directory: 'cd /home/base/Documents/Git/Projekte/CelebFaceMatcher/h5_to_pb/h5_to_pb/': 'cd /home/base/Documents/Git/Projekte/CelebFaceMatcher/h5_to_pb/h5_to_pb/'
When using the same command in the terminal, it works just fine. (Same error type is thrown with the actual command I want to run). What do I overlook? Thanks
Edit:
Thanks to Sven, I also tried following:
prog = subprocess.Popen('cd ' + str(Path.cwd()) + '/h5_to_pb/', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
prog.communicate()
if prog.returncode:
raise Exception('program returned error code {0}'.format(prog.returncode))
Unfortunately with the same result.
Upvotes: 1
Views: 819
Reputation: 1974
cd
is not a program, it is a shell command (command for bash
or sh
or even cmd.exe
). You can't call such commands directly, but you can run shell with such commands as argument:
import subprocess
from pathlib import Path
subprocess.run(['bash','-c', 'cd ' + str(Path.cwd()) + '/h5_to_pb/'], capture_output=True)
Where bash
is a shell, -c
— execute next argument as command, and 'cd ' + str(Path.cwd()) + '/h5_to_pb/'
is a command.
Despite capture_output
parameter this run
output of this call is nothing, because cd
prints nothing. You can make also a several commands in one shell call (and getting output):
subprocess.run(['bash','-c', 'cd ' + str(Path.cwd()) + '/h5_to_pb/ ; ls'], capture_output=True)
If you need run some program in different working directory — use cwd
argument of run
method.
Upvotes: 4