Zvonimir Peran
Zvonimir Peran

Reputation: 711

Executing a program located in another directory in Python

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?

Upvotes: 4

Views: 12277

Answers (5)

soumen
soumen

Reputation: 66

Another alternative is to join the two commands.

import subprocess
subprocess.call('cd /home/bin; ./Upgrade', shell=True)

This way you do not need to change the script run directory.

Upvotes: 1

Andersson
Andersson

Reputation: 52665

Try

import os
os.system('python /home/bin/Upgrade')

If your program is not a .py, then just

os.system('/home/bin/Upgrade')

or

os.system('cd /home/bin|./Upgrade')

Upvotes: 0

skyking
skyking

Reputation: 14390

The subprocess module supports setting current working directory for the subprocess, fx:

subprocess.call("./Upgrade", cwd="/home/bin")

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:

subprocess.call("/home/bin/Upgrade")

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.

Upvotes: 4

Marco Milanesio
Marco Milanesio

Reputation: 100

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

Upvotes: 0

Tminer
Tminer

Reputation: 302

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.

import os

os.chdir()
os.chdir('filepath')

Upvotes: 1

Related Questions