在 Python 中执行位于另一个目录中的程序 [英] Executing a program located in another directory in Python

查看:26
本文介绍了在 Python 中执行位于另一个目录中的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一个位于另一个目录中的程序,而不是执行程序的 python 脚本的位置.例如,如果我的 python 脚本位于/home/Desktop 中,而我的程序升级"位于/home/bin 中,我将如何使用 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')

但问题是使用 subprocess.call('cd/home/bin') 实际上并没有改变目录.

But problem is that directory is not actually changed by using subprocess.call('cd /home/bin').

我该如何解决这个问题?

How can I solve this?

推荐答案

子进程模块支持设置子进程当前工作目录,fx:

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

您可能还想使用 subprocess.check_call 函数(如果您想在子进程不返回零返回码时引发异常).

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

您的解决方案的问题是您启动了一个子进程,在该子进程中尝试执行cd/home/bin",然后启动另一个子进程,在其中尝试执行./Upgrade"——当前工作目录之后不受前者目录变化的影响.

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.

请注意,为 call 方法提供 shell 有一些缺点(也有优点).缺点(或优点)是您将获得各种 shell 扩展(通配符等).一个缺点可能是 shell 可能会根据您的平台对命令进行不同的解释.

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.

这篇关于在 Python 中执行位于另一个目录中的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆