Last active
September 17, 2024 03:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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