Coverage for ppedit/cli.py: 80.1%
100 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 17:40 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 17:40 +0000
1"""Command line interface
3See `ppedit` for the command syntax.
5Examples
6--------
8 ppedit convert case14.py case14.glm
9 ppedit convert wecc240.raw wecc240.glm
10 ppedit check case14.glm
11 ppedit serve case14.glm
12 ppedit --version
13 ppedit serve case14.py --geodata case14_geodata.csv
14 ppedit convert case14.py case14.glm --verbose
16`check` outputs `case14.glm: no issues found`; `serve` prints the editor URL
17(with its session token, e.g. `http://localhost:8050/?token=...`) and opens
18it in a browser; `--version` prints `ppedit` and the installed
19version (e.g. `ppedit 0.3.3`); `--verbose` adds `INFO:` messages on stderr
20(files loaded and saved, and with `serve` each HTTP request, which only
21`--verbose` shows).
22"""
24import os
25import sys
26import secrets
27import argparse
28import logging
29import threading
30import warnings
31import webbrowser
33_logger = logging.getLogger(__file__)
35def _version() -> str:
36 from ppedit import __version__ # pylint: disable=import-outside-toplevel
37 return __version__
39def main(argv:list[str]|None=None) -> int:
40 """Command line entry point
42 Arguments
43 ---------
45 - `argv`: command line arguments (default `sys.argv[1:]`)
47 Returns
48 -------
50 - `int`: exit code (0 on success, 1 on error or validation errors)
51 """
52 parser = argparse.ArgumentParser(prog="ppedit",
53 description="Browser-based editor for PYPOWER and module pypower models",
54 epilog="See https://www.eudoxys.com/ppedit for full documentation.")
55 parser.add_argument("command",choices=["serve","convert","check"])
56 parser.add_argument("files",nargs="*",help="case file(s): .py, .json, .glm, or (input only) PSS/E .raw")
57 parser.add_argument("-g","--geodata",help="CSV of bus locations (BUS_I,LAT,LON,...) to add to the case (serve, convert)")
58 parser.add_argument("-p","--port",type=int,default=8050,help="server port (default 8050)")
59 parser.add_argument("--host",default="127.0.0.1",help="interface to listen on (default 127.0.0.1)")
60 parser.add_argument("--no-browser",action="store_true",help="do not open a browser")
61 parser.add_argument("--token",help="session token the editor URL must carry (serve; default: a new random token each start)")
62 parser.add_argument("-d","--debug",action="store_true",help="enable debug logging and traceback on exceptions")
63 parser.add_argument("-v","--verbose",action="store_true",help="enable INFO messages (progress and server requests)")
64 parser.add_argument("-w","--warning",action="store_true",help="enable warning messages from python")
65 parser.add_argument("--version",action="version",version=f"ppedit {_version()}",help="show the ppedit version and exit")
66 args = parser.parse_args(argv)
68 logging.basicConfig()
69 logging.getLogger().setLevel(logging.DEBUG if args.debug
70 else logging.INFO if args.verbose else logging.WARNING)
71 # werkzeug sets its logger to INFO unless it has a level; request lines only with --verbose
72 logging.getLogger("werkzeug").setLevel(logging.INFO if args.verbose else logging.WARNING)
73 if not args.warning: 73 ↛ 76line 73 didn't jump to line 76 because the condition on line 73 was always true
74 warnings.simplefilter("ignore")
76 try:
77 from ppedit.case import Case # pylint: disable=import-outside-toplevel
78 if args.command == "convert":
79 if len(args.files) != 2:
80 raise ValueError("convert needs INPUT and OUTPUT files")
81 case = Case.load(args.files[0])
82 for note in case.notes:
83 print(f"WARNING [ppedit]: {note}",file=sys.stderr)
84 if args.geodata:
85 case.load_geodata(args.geodata)
86 case.save(args.files[1])
87 return 0
88 if args.command == "check":
89 if len(args.files) != 1: 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 raise ValueError("check needs one FILE")
91 issues = Case.load(args.files[0]).validate()
92 for issue in issues:
93 where = issue["table"] + (f" row {issue['row']+1}" if issue["row"] is not None else "")
94 print(f"{issue['level'].upper()} [{where}]: {issue['message']}")
95 if not issues:
96 print(f"{args.files[0]}: no issues found")
97 return 1 if any(x["level"] == "error" for x in issues) else 0
98 # serve
99 from ppedit.server import create_app # pylint: disable=import-outside-toplevel
100 from werkzeug.serving import make_server # pylint: disable=import-outside-toplevel
101 if len(args.files) > 1: 101 ↛ 102line 101 didn't jump to line 102 because the condition on line 101 was never true
102 raise ValueError("serve takes at most one FILE")
103 case,path = None,None
104 if args.files: 104 ↛ 105line 104 didn't jump to line 105 because the condition on line 104 was never true
105 path = os.path.abspath(args.files[0])
106 if os.path.exists(path):
107 case = Case.load(path)
108 for note in case.notes:
109 print(f"WARNING [ppedit]: {note}",file=sys.stderr)
110 else:
111 case = Case(name=os.path.splitext(os.path.basename(path))[0])
112 if args.geodata: 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true
113 case = case or Case(name="untitled")
114 case.load_geodata(args.geodata)
115 token = args.token if args.token is not None else secrets.token_urlsafe(16)
116 if not token or not token.isascii() or not all(c.isalnum() or c in "-_." for c in token):
117 raise ValueError("--token must be letters, digits, '-', '_' or '.'")
118 server = None
119 app = create_app(case,path,allow_remote=args.host not in ("127.0.0.1","localhost","::1"),
120 shutdown=lambda: server.shutdown(),token=token)
121 server = make_server(args.host,args.port,app,threaded=True)
122 url = f"http://{'localhost' if args.host in ('127.0.0.1','0.0.0.0') else args.host}:{args.port}/?token={token}"
123 print(f"")
124 print(f"ppedit: create or edit power system models in your browser")
125 print(f"")
126 print(f" File... {path or 'new case'}")
127 print(f" URL.... {url}")
128 print(f"")
129 print(f" Ctrl-C to stop server")
130 if not args.no_browser: 130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true
131 threading.Timer(1.0,lambda: webbrowser.open(url)).start()
132 try:
133 server.serve_forever()
134 except KeyboardInterrupt:
135 pass
136 finally:
137 server.server_close()
138 print(f"")
139 print(f"ppedit: thanks for using ppedit!")
140 print(f"")
141 return 0
142 except Exception as err: # pylint: disable=broad-exception-caught
143 if args.debug: 143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true
144 raise
145 print(f"ERROR [ppedit]: {err}",file=sys.stderr)
146 return 1
148if __name__ == "__main__": 148 ↛ 149line 148 didn't jump to line 149 because the condition on line 148 was never true
149 sys.exit(main())