我的主要问题是我正在尝试启动一个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
而不是默认主文件夹开始执行?
答案 0 :(得分:1)
我从没使用过ezsheets或.command文件,但看来您只需要change the working directory:
import os
os.chdir('/username/documents/spreadsheets')
答案 1 :(得分:0)
下面的代码说明了一些可能有用的路径处理技术。
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}")