Executing a program located in another directory i

2019-04-15 16:33发布

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?

5条回答
你好瞎i
2楼-- · 2019-04-15 17:06

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')
查看更多
Explosion°爆炸
3楼-- · 2019-04-15 17:17

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.

查看更多
一纸荒年 Trace。
4楼-- · 2019-04-15 17:18

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

查看更多
戒情不戒烟
5楼-- · 2019-04-15 17:24

Another alternative is to join the two commands.

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

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

查看更多
该账号已被封号
6楼-- · 2019-04-15 17:29

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')
查看更多
登录 后发表回答