【问题标题】:Using Python 2.7 to call an application in a sub folder of the folder containing the .py使用 Python 2.7 在包含 .py 的文件夹的子文件夹中调用应用程序
【发布时间】:2017-07-21 09:49:36
【问题描述】:

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

对不起,如果这似乎是一个新手问题,但如果我得到这个答案,它真的会帮助我

【问题讨论】:

    标签: python path directory


    【解决方案1】:

    只需添加相对路径:

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

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

    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;
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 所以在我的例子中是: sys.path.append(os.path.join(os.path.dirname(IJ.exe), '/recources')) ??我不完全理解,再次,我对编程很陌生
      • file 代替上面的 IJ.exe(这里没有显示 2 dunder)。这部分用于脚本的当前目录。我猜资源前没有斜线
      • 会努力做到的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多