Skip to content

Commit

Permalink
Merge pull request #7 from RBerga06/develop
Browse files Browse the repository at this point in the history
  • Loading branch information
RBerga06 authored Jul 21, 2022
2 parents 5cb90c9 + 1289880 commit 3da438d
Show file tree
Hide file tree
Showing 19 changed files with 1,245 additions and 378 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ __pycache__/
*.py[cod]
*$py.class

# Cython-generated C/C++ files
*.c
*.cpp

# Cython-generated compilation annotations
*.html

# C extensions
*.so

Expand Down
1 change: 1 addition & 0 deletions .pep8speaks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pycodestyle:
- E241 # multiple spaces after ':'
- E704 # multiple statements on one line (def)
- W503 # line break before binary operator
- E722 # do not use bare 'except'
# - E402 # module level import not at top of file
# - E731 # do not assign a lambda expression, use a def
# - C406 # Unnecessary list literal - rewrite as a dict literal.
Expand Down
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"python.linting.enabled": true,
"cSpell.language": "it-IT,en-GB"
}
31 changes: 26 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,18 +145,39 @@ python -O src/nome-del-file.py
```

Di default, la libreria per leggere i dati è `PyROOT` (quando installata); altrimenti, viene utilizzata `uproot`.
Per forzare l'utilizzo di `uproot` anche quando `PyROOT` è installata, impostare la variabile d'ambiente `FORCE_UPROOT`.
Per forzare l'utilizzo di `uproot` anche quando `PyROOT` è installata, impostare la variabile d'ambiente `FORCE_UPROOT` (il valore assegnato non è importante, basta che in Python si auto-converta in `True` – per esempio, `1`, `42`, `__import__("math").pi` \[sconsigliato], o `True` stesso).
Per disabilitare `FORCE_UPROOT`, assegnare un valore che in Python si auto-converta in `False`, come `0`, `list()` \[sconsigliato] o `False` stesso. Alternativamente, rimuovere la variabile d'ambiente (assegnandole un valore nullo, `FORCE_UPROOT=`).

Su UNIX:

```bash
export FORCE_UPROOT=1 # Anche '=True' va bene
# Imposta la variabile d'ambiente per tutta la sessione
export FORCE_UPROOT=1
# Esegui normalmente i programmi
python src/file.py
```
# Più avanti, per disattivarla, si dovrà rimuoverla...
export FORCE_UPROOT=""
# ... o impostarla a `False`
export FORCE_UPROOT=0

O, per evitare di usare `export`:
# --- oppure ----

```bash
# Imposta la variabile d'ambiente solo per questo comando
FORCE_UPROOT=1 python src/file.py
# Dopo che il comando è stato eseguito, la variabile d'ambiente *non* è più impostata.
```

Su Windows:

```powershell
# Imposta la variabile d'ambiente
set FORCE_UPROOT=1
# Esegui normalmente i programmi
python src/file.py
# Più avanti, la si dovrà rimuovere...
set FORCE_UPROOT=
# ... o impostare a `False`
set FORCE_UPROOT=0
```

### Stagisti
Expand Down
201 changes: 201 additions & 0 deletions compile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Un programma di utility che compila in Cython i moduli richiesti.
python compile.py [COMMAND] [ARGUMENTS]
python compile.py help
python compile.py commands
"""
import os
from pathlib import Path
import sys
from typing import NoReturn
import subprocess
import shutil


CYTHON_VERSION = "3.0.0a10"


def _cython_dep_error() -> NoReturn:
print(f"""\
ERROR: No compatible Cython version found.
Please install this Cython version:
pip install Cython={CYTHON_VERSION}
""", file=sys.stderr)
sys.exit(1)


try:
import cython
from Cython.Build.Cythonize import main as cythonize
except ModuleNotFoundError:
_cython_dep_error()
else:
if cython.__version__ != CYTHON_VERSION:
_cython_dep_error()


SRC = Path(__file__).parent / "src"
TARGETS = [f.stem for f in SRC.glob("*.py")]
PYTHON_FRAMES: bool = True


def list_targets() -> None:
"""Ottieni una lista di tutti i moduli disponibili.
python compile.py list
"""
print("all", *TARGETS, sep=", ")


def build(*targets: str) -> int:
"""Compila con Cython i moduli specificati.
python compile.py build *[TARGETS]
python compile.py build log root stagisti
"""
if "all" in targets:
return build(*TARGETS)
for target in targets:
if target not in TARGETS:
continue
sources = [str(f.resolve()) for f in [SRC / f"{target}.py", SRC / f"{target}.pxd"] if f.exists()]
print(f"--> Building {target} ({', '.join(sources)})")
try:
args = [
"-3i", "--annotate-fullc",
"-j", str(os.cpu_count()),
# "-X", f"linetrace={PYTHON_FRAMES}",
# "-X", f"profile={PYTHON_FRAMES}",
"--lenient",
*sources,
]
print(f"$ cythonize {' '.join(args)}")
cythonize(args)
except SystemExit as e:
return e.code
return 0


def rm(*paths: str | Path):
"""Elimina i file e le cartelle in `paths`."""
for path in paths:
if not isinstance(path, Path):
path = Path(path)
if not path.exists():
continue
print(f"Removing {path.relative_to(SRC.parent)}")
if path.is_dir():
shutil.rmtree(path)
else:
os.unlink(path)


def clean(*targets) -> None:
"""Rimuovi gli elementi creati durante la `build`.
python compile.py clean *[TARGETS]
python compile.py clean root log
python compile.py clean all
python compile.py clean
"""
if not targets or "all" in targets:
rm(
*SRC.glob("*.c"),
*SRC.glob("*.html"),
*SRC.glob("*.so"),
*SRC.glob("*.pyd"),
SRC / "build",
)
return
for target in targets:
rm(
SRC / f"{target}.c",
SRC / f"{target}.html",
*SRC.glob(f"{target}.*.so"),
*SRC.glob(f"build/lib.*/{target}.*.so"),
)


RUN = r"""\
print(f'\n--> Importing $$')
import $$
func = getattr($$, 'main', getattr($$, 'test', None))
print(f'\n--> $$ has been imported from {$$.__file__}')
if func:
print(f'--> Running $$.{func.__name__}()')
func()
"""


def run(*argv: str) -> int:
"""Compila ed esegui il modulo dato con gli argomenti dati.
python compile.py run *[OPZIONI PYTHON] [PROGRAMMA] *[ARGOMENTI/OPZIONI PROGRAMMA]
python compile.py run -O root -vv data.root
"""
args = list(argv)
target = ""
for arg in args:
if not arg.startswith("-"):
target = arg
break
if not target:
raise ValueError("A target must be specified!")
build(target)
os.chdir(SRC)
index = args.index(target)
args[index] = RUN.replace("$$", target)
args.insert(index, "-c")
args.insert(0, sys.executable)
return subprocess.run(args, check=False).returncode


def help(cmd: str | None = None, /) -> None:
"""Get help for a given command.
python compile.py help [COMMAND]
python compile.py help commands
"""
if cmd is None:
print(__doc__)
help("help")
else:
print(COMMANDS.get(cmd, help).__doc__)


def list_commands() -> None:
"""List the available commands.
python compile.py commands
"""
print(*COMMANDS, sep=" ")


COMMANDS = dict(
run=run,
build=build,
clean=clean,
list=list_targets,
help=help,
commands=list_commands,
)


def cli(argv: list[str]) -> int | None:
"""Interfaccia da riga di comando."""
if len(argv) < 1:
return help()
first = argv.pop(0)
if first in COMMANDS:
cmd = COMMANDS[first]
else:
cmd = build
argv = [first] + argv
return cmd(*argv)


if __name__ == "__main__":
sys.exit(cli(sys.argv[1:]) or 0)
27 changes: 26 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,33 @@ ignore = [
"E221", # multiple spaces before operator
"E241", # multiple spaces after ':'
"E704", # multiple statements on one line (def)
"W503" # line break before binary operator
"E722", # bare except
"W503", # line break before binary operator
]
in-place = true
recursive = true
aggressive = 3


[tool.pylint.main]
max-line-length = 120

[tool.pylint."MESSAGES CONTROL"]
disable = [
# Errors
# Warnings
"W0123", # use of eval
"W0621", # Redefining name '*' from outer scope
"W0622", # Redefining built-in '*'
"W0702", # No exception type(s) specified
"W1203", # Use %s formatting in logging functions
# Conventions
"C0103", # Variable name "*" doesn't conform to snake_case naming style
# Refactoring
"R0903", # too few public methods (*/2)
"R0912", # too many branches (*/12)
"R0914", # Too many local variables (*/15)
"R0915", # Too many statements (*/50)
"R1704", # Redefining argument with the local name '*'
"E0611", # No name * in module *
]
5 changes: 5 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[pycodestyle]
max-line-length = 120
ignore = E221,E241,E704,E722,W503
statistics = True

Loading

0 comments on commit 3da438d

Please sign in to comment.