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

View File

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