pytailwindcss
pytailwindcss provides a Python-installable wrapper for the standalone Tailwind CSS CLI, enabling developers to use Tailwind CSS in Python projects without requiring Node.js. It bundles a specific version of the Tailwind CLI executable. The current version is 0.3.0, and releases are tied to updates of the underlying Tailwind CSS CLI or Python API improvements.
Common errors
-
ModuleNotFoundError: No module named 'pytailwindcss'
cause The `pytailwindcss` package has not been installed in your current Python environment.fixRun `pip install pytailwindcss`. -
FileNotFoundError: [Errno 2] No such file or directory: 'tailwind'
cause You are attempting to run the `tailwind` command directly from your system shell. `pytailwindcss` provides a Python API (`run_tailwind_cli`), but does not install a global `tailwind` executable to your system's PATH.fixUse the Python API: `from pytailwindcss import run_tailwind_cli` and call it as a function within your Python script. -
Tailwind CSS build failed with return code X
cause The underlying Tailwind CSS CLI command failed. This often indicates issues with the input CSS path (`-i`), output CSS path (`-o`), the `tailwind.config.js` configuration (e.g., incorrect `content` paths), or syntax errors in your CSS.fixExamine the `stdout` and `stderr` output from the `run_tailwind_cli` result object for specific error messages from the Tailwind CLI. Verify your `tailwind.config.js` and input CSS files are correctly configured and accessible.
Warnings
- gotcha The `pytailwindcss` package bundles a specific version of the standalone Tailwind CSS CLI. To update the Tailwind CSS CLI version (e.g., to get new features or bug fixes from Tailwind CSS itself), you must update the `pytailwindcss` Python package itself.
- gotcha When using `run_tailwind_cli`, ensure that input (`-i`) and output (`-o`) CSS paths, as well as the `content` paths in your `tailwind.config.js`, are correctly resolved. These paths are relative to the current working directory of the Python script or absolute paths.
- gotcha The `run_tailwind_cli` function expects a list of strings for CLI arguments (e.g., `['-i', 'input.css', '--minify']`), not a single string that would be parsed by a shell. Passing arguments as a single string will lead to incorrect parsing.
Install
-
pip install pytailwindcss
Imports
- run_tailwind_cli
from pytailwindcss import run_tailwind_cli
Quickstart
import os
from pathlib import Path
from pytailwindcss import run_tailwind_cli
import sys
# Define a temporary directory for the quickstart example
temp_dir = Path("pytailwindcss_quickstart_temp")
temp_dir.mkdir(exist_ok=True)
# Create dummy files for the quickstart to be runnable
config_path = temp_dir / "tailwind.config.js"
input_css_path = temp_dir / "input.css"
output_css_path = temp_dir / "output.css"
templates_dir = temp_dir / "templates"
templates_dir.mkdir(exist_ok=True)
html_path = templates_dir / "index.html"
# Write dummy config
config_path.write_text("""
module.exports = {
content: ['./templates/*.html'],
theme: {
extend: {},
},
plugins: [],
}
""")
# Write dummy input CSS
input_css_path.write_text("""
@tailwind base;
@tailwind components;
@tailwind utilities;
h1 { @apply text-blue-600; }
""")
# Write dummy HTML
html_path.write_text("""
<!DOCTYPE html>
<html>
<head>
<link href="output.css" rel="stylesheet">
</head>
<body>
<h1 class="text-xl font-bold">Hello Tailwind</h1>
</body>
</html>
""")
original_cwd = Path.cwd()
os.chdir(temp_dir) # Change CWD for the CLI to find files relative to temp_dir
print(f"Running Tailwind CSS build in {temp_dir}...")
try:
# Example arguments for a basic build
# Using relative paths because we changed CWD
result = run_tailwind_cli([
'-i', 'input.css',
'-o', 'output.css',
'--minify'
])
if result.returncode == 0:
print("Tailwind CSS build successful!")
if output_css_path.exists():
print("\nGenerated output.css (first 200 chars):\n")
print(output_css_path.read_text()[:200])
else:
print("output.css not found, but build reported success.")
else:
print(f"Tailwind CSS build failed with return code {result.returncode}.")
if result.stdout:
print(f"Stdout:\n{result.stdout.decode(sys.getdefaultencoding())}")
if result.stderr:
print(f"Stderr:\n{result.stderr.decode(sys.getdefaultencoding())}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
os.chdir(original_cwd) # Restore original CWD
# Clean up dummy files
print(f"\nCleaning up temporary files in {temp_dir}...")
for f in temp_dir.iterdir():
if f.is_file():
f.unlink()
elif f.is_dir():
for sub_f in f.iterdir():
sub_f.unlink()
f.rmdir()
temp_dir.rmdir()
print("Cleanup complete.")