简体   繁体   中英

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?

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.

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')

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.

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')

或者您可以查看python相对导入,具体取决于它的作用以及如何在Update dir中构建脚本

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM