【问题标题】:Launching a python script from a different directory从不同的目录启动 python 脚本
【发布时间】:2020-10-31 23:18:57
【问题描述】:

我的主要问题是我正在尝试启动一个 Python 脚本(我在顶部使用了 #!/usr/local/bin/python3,将其更改为 .command 文件,并确保运行 chmod +x),它使用了一个模块 (ezsheets)引用特定文件夹进行身份验证,但我无法让它自动运行,因为当我启动它引用主文件夹的脚本时。

更具体地说,我在名为电子表格的文件夹中有一个脚本,在该文件夹中我有相应的 Google 帐户权限文件。我将所有电子表格更改文件都存储在其中,因为 EZsheets 似乎需要这样做才能验证身份验证。

但是,当我将其作为 .command 文件运行时,我认为问题在于它会在主文件夹中打开我的终端,然后运行脚本,然后出现以下错误:

    raise EZSheetsException(
ezsheets.EZSheetsException: Can't find credentials file at /Users/myusername/credentials-sheets.json

找不到,因为它位于/username/documents/spreadsheets

当我在终端的正确目录中并手动运行文件时,它工作得很好。

理想情况下,我希望能够从/spreadsheets 启动此脚本并将我的所有电子表格脚本留在其中,因为它具有我已经验证的权限文件 - 有什么方法可以启动执行的脚本从/username/documents/spreadsheets 开始而不是默认的主文件夹?

【问题讨论】:

    标签: python macos shell


    【解决方案1】:

    我从未使用过 ezsheets 或 .command 文件,但看起来您只需要 change the working directory

    import os
    
    os.chdir('/username/documents/spreadsheets')
    

    【讨论】:

    • 是的,你完全正确!我把它放在我的脚本文件的顶部来重定向目录,它工作得很好。谢谢!
    【解决方案2】:

    下面的代码解释了一些可能有用的路径处理技术。

    import os
    
    # At start the current path is where you execute the script,
    # and not where the script is saved.
    current_path = os.getcwd()
    print(f"You are now in {current_path}")
    
    # So get the path of the directory where the script actualy is.
    script_path = os.path.dirname(os.path.realpath(__file__))
    print(f"The script {__file__} is stored in {script_path}")
    
    # Or the path to the spreadsheets.
    spreadsheets_path = "/username/documents/spreadsheets"
    
    # Now change the current path.
    os.chdir(script_path)
    
    # And check that it is correct.
    current_path = os.getcwd()
    print(f"You are now in {current_path}")
    

    【讨论】:

    • 是的,将 os.chdir 放在顶部正是我所需要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多