|
4 | 4 |
|
5 | 5 |
|
6 | 6 | # standard library
|
7 |
| -from logging import getLogger |
| 7 | +import os |
| 8 | +import sys |
| 9 | +from logging import basicConfig, INFO, getLogger |
| 10 | +from logging import FileHandler, StreamHandler |
8 | 11 | from socket import socket, AF_INET, SOCK_STREAM
|
9 | 12 | from typing import Optional, Union
|
10 | 13 | from pathlib import Path
|
@@ -100,3 +103,44 @@ def connect(host: str, port: int, timeout: Optional[float] = TIMEOUT) -> CustomS
|
100 | 103 | def shorten(string: str, width: int, placeholder: str = "...") -> str:
|
101 | 104 | """Same as textwrap.shorten(), but compatible with string without whitespaces."""
|
102 | 105 | return string[:width] + (placeholder if string[width:] else "")
|
| 106 | + |
| 107 | + |
| 108 | +# main script |
| 109 | +if __name__ == "__main__": |
| 110 | + """Mini tool to send command or line(s) written in a file. |
| 111 | +
|
| 112 | + Usage: |
| 113 | + $ export FG_HOST=<host name> |
| 114 | + $ export FG_PORT=<port number> |
| 115 | + $ export PG_HOST=<host name> |
| 116 | + $ export PG_PORT=<port number> |
| 117 | + $ poetry run python scpi.py [FG|PG] <file path or command> |
| 118 | +
|
| 119 | + """ |
| 120 | + basicConfig( |
| 121 | + level=INFO, |
| 122 | + format="%(asctime)s %(levelname)s %(message)s", |
| 123 | + handlers=(StreamHandler(), FileHandler("scpi.log")), |
| 124 | + ) |
| 125 | + |
| 126 | + device = sys.argv[1] |
| 127 | + path_or_cmd = sys.argv[2] |
| 128 | + |
| 129 | + if device.upper() == "FG": |
| 130 | + host = os.environ["FG_HOST"] |
| 131 | + port = os.environ["FG_PORT"] |
| 132 | + elif device.upper() == "PG": |
| 133 | + host = os.environ["PG_HOST"] |
| 134 | + port = os.environ["PG_PORT"] |
| 135 | + else: |
| 136 | + raise ValueError("Device must be either FG or PG.") |
| 137 | + |
| 138 | + if Path(path_or_cmd).exists(): |
| 139 | + with connect(host, port) as sock: |
| 140 | + sock.send_from(path_or_cmd) |
| 141 | + else: |
| 142 | + with connect(host, port) as sock: |
| 143 | + sock.send(path_or_cmd) |
| 144 | + |
| 145 | + if path_or_cmd.endswith(KWD_QUERY): |
| 146 | + sock.recv() |
0 commit comments