Skip to main content
 首页 » 编程设计

python之使用 Python 2.7 在包含 .py 的文件夹的子文件夹中调用应用程序

2025年02月15日7soundcode

我想知道是否有一种方法可以调用现有文件夹子文件夹中的外部应用程序(看起来像图 1,而不是图 2)。我知道我可以让它打开一个特定的文件路径,但是当文件夹位于任何目录中时,我需要它在任何计算机上工作,这在另一台计算机上根本无法工作。

图 1: https://gyazo.com/4c98428836e03e0b7a3e2c6bf2c0d9e1

图 2: https://gyazo.com/8e0263ee7918e2fa26653a1dcc6187c7

我目前正在使用看起来像这样的代码来启动它们,但它只有在同一文件夹中时才有效:

def Button3(): 
    os.startfile('procexp.exe') 
def Button4(): 
    os.startfile('IJ.exe') 
def Button5(): 
    os.startfile('Br.exe') 
def Button6(): 
    os.startfile('Cs.exe') 

对不起,如果这看起来有点新手问题,但如果我能得到答案,那真的会帮助我

请您参考如下方法:

只需添加相对路径:

. 表示从 present-working-directory 开始(通常是程序启动的位置)。

因此,如果您从主程序所在的同一文件夹启动主程序:

def Button3(): 
    os.startfile('./resources/procexp.exe') 
def Button4(): 
    os.startfile('./resources/IJ.exe') 
def Button5(): 
    os.startfile('./resources/Br.exe') 
def Button6(): 
    os.startfile('./resources/Cs.exe') 

然而通常情况并非如此,大多数情况下您会从任何地方启动程序(因为它在您的 PATH 环境中)或通过提供完整路径来启动程序。在那种情况下,您想找出程序的安装位置,然后找出相对于它放置资源的位置:

特殊变量 __file__ 包含您的脚本所在的位置,包括它的路径。您可以使用os.path 包中的dirname 方法获取目录名称:

     program_dir = os.path.dirname(__file__) 

然后你可以相对于那个工作:

     resource_dir = os.path.join(program_dir, 'resources') 

os.path.join 是一种以操作系统对抗方式将路径位连接在一起的方法。

所以最终你的程序可以变成:

     resource_dir = os.path.join(os.path.dirname(__file__), 'resources'); 
 
def Button3(): 
    os.startfile(os.path.join(resource_dir, 'procexp.exe')) 
def Button4(): 
    os.startfile(os.path.join(resource_dir, 'IJ.exe')) 
def Button5(): 
    os.startfile(os.path.join(resource_dir, 'Br.exe')) 
def Button6(): 
    os.startfile(os.path.join(resource_dir, 'Cs.exe')) 

等等

当然,为了使用 os.path 你需要导入它:

  import os;