Use main function, avoid unnecessary trailing underscores

This commit is contained in:
Davte 2020-04-11 20:55:26 +02:00
parent 4f01831169
commit b77de07d6e
2 changed files with 90 additions and 79 deletions

View File

@ -281,7 +281,7 @@ def get_file_path(path, action='receive'):
logging.error(f"Invalid file: `{path}`")
if __name__ == '__main__':
def main():
# noinspection SpellCheckingInspection
log_formatter = logging.Formatter(
"%(asctime)s [%(module)-15s %(levelname)-8s] %(message)s",
@ -290,6 +290,9 @@ if __name__ == '__main__':
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
# noinspection PyUnresolvedReferences
asyncio.selector_events.logger.setLevel(logging.ERROR)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
console_handler.setLevel(logging.DEBUG)
@ -298,14 +301,14 @@ if __name__ == '__main__':
# Parse command-line arguments
cli_parser = argparse.ArgumentParser(description='Run client',
allow_abbrev=False)
cli_parser.add_argument('--_host', type=str,
cli_parser.add_argument('--host', type=str,
default=None,
required=False,
help='server address')
cli_parser.add_argument('--_port', type=int,
cli_parser.add_argument('--port', type=int,
default=None,
required=False,
help='server _port')
help='server port')
cli_parser.add_argument('--action', type=str,
default=None,
required=False,
@ -328,80 +331,80 @@ if __name__ == '__main__':
nargs='*',
help='[S]end or [R]eceive (see `action`)')
args = vars(cli_parser.parse_args())
_host = args['_host']
_port = args['_port']
_action = get_action(args['action'])
_file_path = args['path']
_password = args['password']
_token = args['token']
host = args['host']
port = args['port']
action = get_action(args['action'])
file_path = args['path']
password = args['password']
token = args['token']
# If _host and _port are not provided from command-line, try to import them
if _host is None:
# If host and port are not provided from command-line, try to import them
if host is None:
try:
from config import host as _host
from config import host
except ImportError:
_host = None
if _port is None:
host = None
if port is None:
try:
from config import port as _port
from config import port
except ImportError:
_port = None
# Take `s`, `r` etc. from command line as `_action`
if _action is None:
port = None
# Take `s`, `r` etc. from command line as `action`
if action is None:
for arg in args['others']:
_action = get_action(arg)
if _action:
action = get_action(arg)
if action:
break
if _action is None:
if action is None:
try:
from config import action as _action
_action = get_action(_action)
from config import action
action = get_action(action)
except ImportError:
_action = None
if _file_path is None:
action = None
if file_path is None:
try:
from config import file_path as _file_path
_file_path = get_action(_file_path)
from config import file_path
file_path = get_action(file_path)
except ImportError:
_file_path = None
if _password is None:
file_path = None
if password is None:
try:
from config import password as _password
from config import password
except ImportError:
_password = None
if _token is None:
password = None
if token is None:
try:
from config import token as _token
from config import token
except ImportError:
_token = None
token = None
# If import fails, prompt user for _host or _port
while _host is None:
_host = input("Enter _host:\t\t\t\t\t\t")
while _port is None:
# If import fails, prompt user for host or port
while host is None:
host = input("Enter host:\t\t\t\t\t\t")
while port is None:
try:
_port = int(input("Enter _port:\t\t\t\t\t\t"))
port = int(input("Enter port:\t\t\t\t\t\t"))
except ValueError:
logging.info("Invalid _port. Enter a valid _port number!")
_port = None
while _action is None:
_action = get_action(
logging.info("Invalid port. Enter a valid port number!")
port = None
while action is None:
action = get_action(
input("Do you want to (R)eceive or (S)end a file?\t\t")
)
while _file_path is None:
_file_path = get_file_path(
path=input(f"Enter file to {_action}:\t\t\t\t\t\t"),
action=_action
while file_path is None:
file_path = get_file_path(
path=input(f"Enter file to {action}:\t\t\t\t\t\t"),
action=action
)
if _password is None:
if password is None:
logging.warning(
"You have provided no password for file encryption.\n"
"Your file will be unencoded unless you provide a password in "
"config file."
)
if _token is None and _action == 'send':
if token is None and action == 'send':
# Generate a random [6-10] chars-long alphanumerical token
_token = ''.join(
token = ''.join(
random.SystemRandom().choice(
string.ascii_uppercase + string.digits
)
@ -409,19 +412,19 @@ if __name__ == '__main__':
)
logging.info(
"You have not provided a token for this connection.\n"
f"A token has been generated for you:\t\t{_token}\n"
f"A token has been generated for you:\t\t{token}\n"
"Your peer must be informed of this token.\n"
"For future connections, you may provide a custom token writing "
"it in config file."
)
while _token is None or not (6 <= len(_token) <= 10):
_token = input("Please enter a 6-10 chars token.\t\t\t\t")
while token is None or not (6 <= len(token) <= 10):
token = input("Please enter a 6-10 chars token.\t\t\t\t")
loop = asyncio.get_event_loop()
client = Client(
host=_host,
port=_port,
password=_password,
token=_token
host=host,
port=port,
password=password,
token=token
)
try:
from config import certificate
@ -431,19 +434,24 @@ if __name__ == '__main__':
client.set_ssl_context(_ssl_context)
except ImportError:
logging.warning("Please consider using SSL.")
certificate, key = None, None
# noinspection PyUnusedLocal
certificate = None
logging.info("Starting client...")
if _action == 'send':
if action == 'send':
loop.run_until_complete(
client.run_sending_client(
file_path=_file_path
file_path=file_path
)
)
else:
loop.run_until_complete(
client.run_receiving_client(
file_path=_file_path
file_path=file_path
)
)
loop.close()
logging.info("Stopped client")
if __name__ == '__main__':
main()

View File

@ -234,6 +234,9 @@ def main():
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
# noinspection PyUnresolvedReferences
asyncio.selector_events.logger.setLevel(logging.ERROR)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
console_handler.setLevel(logging.DEBUG)
@ -251,34 +254,34 @@ def main():
required=False,
help='server port')
args = vars(parser.parse_args())
_host = args['host']
_port = args['port']
host = args['host']
port = args['port']
# If _host and _port are not provided from command-line, try to import them
if _host is None:
# If host and port are not provided from command-line, try to import them
if host is None:
try:
from config import host as _host
from config import host
except ImportError:
_host = None
if _port is None:
host = None
if port is None:
try:
from config import port as _port
from config import port
except ImportError:
_port = None
port = None
# If import fails, prompt user for _host or _port
while _host is None:
_host = input("Enter host:\t\t\t\t\t\t")
while _port is None:
# If import fails, prompt user for host or port
while host is None:
host = input("Enter host:\t\t\t\t\t\t")
while port is None:
try:
_port = int(input("Enter port:\t\t\t\t\t\t"))
port = int(input("Enter port:\t\t\t\t\t\t"))
except ValueError:
logging.info("Invalid port. Enter a valid port number!")
_port = None
port = None
server = Server(
host=_host,
port=_port,
host=host,
port=port,
)
try:
# noinspection PyUnresolvedReferences