Skip to content

Instantly share code, notes, and snippets.

@shner-elmo
Last active September 17, 2024 03:00
Show Gist options
  • Save shner-elmo/b2639a4d1e04ceafaad120acfb31213c to your computer and use it in GitHub Desktop.
Save shner-elmo/b2639a4d1e04ceafaad120acfb31213c to your computer and use it in GitHub Desktop.
A simple function to call ruff within a Python script to format a string
import subprocess
from ruff.__main__ import find_ruff_bin
def ruff_format(code: str) -> str:
ruff_args = [
find_ruff_bin(),
'format',
'--stdin-filename',
'foo.py', # you can pass any random string, it wont use it...
# these two lines are optional, but this is how you can pass the config for ruff
'--config',
'pyproject.toml',
]
proc = subprocess.run(ruff_args, input=code, text=True, capture_output=True)
proc.check_returncode() # raise an Exception if return code is not 0
return proc.stdout
# tested on ruff 0.5.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment