nickrallison / obsidian-python-scripter

GNU General Public License v3.0
44 stars 8 forks source link

Obsidian Python Scripter

Summary

This is a program to quickly allow you to run your own Python scripts from inside Obsidian. To get started enable this plugin, it will create a scripts/python folder inside your designated .obsidian folder. For each script it will add a custom command to the obsidian commands panel.

Requirements

commandwindow

Plugin Direction

This plugin passes 2 optional arguments to the script, argument 1 is the absolute path to the obsidian root folder, argument 2 is the path to the open file if it is open, otherwise an empty path is sent e.g. python \Users\nick\Documents\Vault\.obsidian\scripts\python\main.py \Users\nick\Documents\Vault dir1\file1.md

More optional arguments can be added, as well as the ability to prompt the user for arguments.

These can be used by the script as liked.

Here is a starting point for a python script: main.py

# main.py
import sys
import os

python_script = sys.argv[0]
file_path = sys.argv[2]
vault_path = sys.argv[1]

abs_file_path = os.path.abspath(os.path.join(vault_path, file_path))

print(f"This is the open file: {abs_file_path}")

Environment

If you don't want to add secrets directly to your scripts, you can store them elsewhere in an environment file, which can then be imported at run time.

Example Env File:

SECRET_PASSWORD=supersecretword
OTHER_PASSWORD=password

Settings

You have the ability to change the default python script location in settings. Additionally you have the ability to change the default python executable, or can configure python executables per script if you would like to use virtual environments. i.e. Python Exe: C:\Users\nickr\Documents\Projects\Scratch.venv\Scripts\python.exe

Debugging

If your script fails to run. An error is shown in the top right of obsidian and in the developer console which can be found with the following hotkeys: "ctrl" + "shift" + "i" on Windows, or "cmd" + "option" + "i" on MacOS.