I need to execute a program that is located in another directory than location of python script which executes a program. For example, if I my python script is located in /home/Desktop and my program 'Upgrade' is located in /home/bin, how would I execute it using python script? I tried it this way:
import subporcess
subprocess.call('cd /home/bin')
subprocess.call('./Upgrade')
But problem is that directory is not actually changed by using subprocess.call('cd /home/bin').
How can I solve this?
You can change directory using os. The python script will remain in the folder it was created but will run processes based on the new directory.
The subprocess module supports setting current working directory for the subprocess, fx:
If you don't care about the current working directory of your subprocess you could of course supply the fully qualified name of the executable:
You might also want to use the
subprocess.check_call
function (if you want to raise an exception if the subprocess does not return a zero return code).The problem with your solution is that you start a subprocess in which you try to execute "cd /home/bin" and then start ANOTHER subprocess in which you try to execute "./Upgrade" - the current working directory of the later is not affected by the change of directory in the former.
Note that supplying shell to the
call
method has a few drawbacks (and advantages too). The drawback (or advantage) is that you'll get various shell expansions (wildcard and such). One disadvantage may be that the shell may interpret the command differently depending on your platform.or you can have a look at the python relative import, depending on what it does and how is built your script in the Update dir
Another alternative is to join the two commands.
This way you do not need to change the script run directory.
Try
If your program is not a
.py
, then justor