使用Python2.7调用包含.py的文件夹的子文件夹中的应用程序

2024-10-01 00:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一种方法可以调用现有文件夹的子文件夹中的外部应用程序(看起来像图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')

抱歉,如果这看起来像一个新手的问题,但它会真的帮助我,如果我得到一个关于这个问题的答案


Tags: 文件方法代码https路径目录文件夹com
2条回答

您必须提供路径并可以使用sys模块,例如

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'relative_path_to_your_file'))

只需添加相对路径:

.表示从当前工作目录(通常是启动程序的位置)开始。你知道吗

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

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

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

特殊变量__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'))

等等

当然为了使用操作系统路径您需要导入它:

  import os;

相关问题 更多 >