0

My main issue is that I'm trying to launch a Python script (I used #!/usr/local/bin/python3 at the top, changed it to .command file, and made sure to run chmod +x) which uses a module (ezsheets) that references a specific folder for authentication, but I can't get it to automatically run as when I launch the script it references the home folder.

More specifically, I have a script in a folder called spreadsheets, and inside that folder I have the appropriate Google account permissions file. I store all my spreadsheet altering files in there as it seems EZsheets requires that in order to verify authentication.

However, when I run it as a .command file, I believe the issue is that it opens my Terminal in the home folder and then runs the script, and I get the following error:

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

It can't find it, because that's located in /username/documents/spreadsheets.

When I am in the right directory in terminal and run the file manually, it works just fine.

Ideally I'd like to be able to launch this script from /spreadsheets and leave all my spreadsheet scripts in there as that has the permission file that I've already authenticated - is there any way to launch the script that executes starting from /username/documents/spreadsheets instead of the default home folder?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
scottyent
  • 3
  • 1

2 Answers2

1

I've never used ezsheets or .command files, but it looks like you just need to change the working directory:

import os

os.chdir('/username/documents/spreadsheets')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Yes, you're exactly right! I put that at the top of my script file to redirect the directory and it worked perfectly. Thanks! – scottyent Nov 02 '20 at 03:10
0

The code below explains some path handling techniques that could be useful.

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}")
nico
  • 1,130
  • 2
  • 12
  • 26