Changed the sys.exit, if not tmpstr, the errorhandling, the creation of the Target Directory, and some PEP8 Styling things too..

This commit is contained in:
georg 2020-12-25 18:27:36 +01:00
parent 5ba2de2f40
commit aba237db2e
2 changed files with 35 additions and 20 deletions

View file

@ -29,11 +29,14 @@ import threading
import urllib3 import urllib3
import logging import logging
import time import time
from urllib3.exceptions import MaxRetryError
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
def print_time(): def print_time():
return time.strftime("%Y-%m-%d %H:%M:%S") return time.strftime("%Y-%m-%d %H:%M:%S")
def check_duration(value): def check_duration(value):
try: try:
value = int(value) value = int(value)
@ -58,7 +61,8 @@ def read_settings(args):
elif sys.platform == 'win32': elif sys.platform == 'win32':
settings_base_dir = os.getenv('LOCALAPPDATA') + os.sep + 'radiorec' settings_base_dir = os.getenv('LOCALAPPDATA') + os.sep + 'radiorec'
elif sys.platform == 'darwin': elif sys.platform == 'darwin':
settings_base_dir = os.getenv('HOME') + os.sep + 'Library' + os.sep + 'Application Support' + os.sep + 'radiorec' settings_base_dir = os.getenv('HOME') + os.sep + 'Library' + os.sep + \
'Application Support' + os.sep + 'radiorec'
settings_base_dir += os.sep settings_base_dir += os.sep
config = configparser.ConfigParser() config = configparser.ConfigParser()
try: try:
@ -106,10 +110,10 @@ def record_worker(stoprec, streamurl, target_dir, args):
while(not stoprec.is_set() and not conn.closed): while(not stoprec.is_set() and not conn.closed):
target.write(conn.read(1024)) target.write(conn.read(1024))
verboseprint(print_time() + " ... Connection closed = " + str(conn.closed)) verboseprint(print_time() + " ... Connection closed = " + str(conn.closed))
conn.release_conn() conn.release_conn()
def record(args): def record(args):
settings = read_settings(args) settings = read_settings(args)
streamurl = '' streamurl = ''
@ -128,27 +132,33 @@ def record(args):
try: try:
remotefile = pool.request('GET', streamurl) remotefile = pool.request('GET', streamurl)
except MaxRetryError: except MaxRetryError:
print('The URL of the station is not found! Check' + args.station + ' in the Settings!') logging.getLogger(__name__).error('The URL of the station is somehow faulty! Check' +
args.station + ' in the Settings!')
sys.exit() sys.exit()
if remotefile.status != 200: if remotefile.status != 200:
print('The URL of the station is somehow faulty! Check' + args.station + ' in the Settings!') logging.getLogger(__name__).error(
sys.exit() 'The URL of the station is somehow faulty! Check' + args.station + ' in the Settings!')
sys.exit(1)
else: else:
for line in remotefile.data.decode().split(): for line in remotefile.data.decode().split():
if not line.startswith('#') and len(line) > 1 and line.endswith('mp3'): if not line.startswith('#') and len(line) > 1 and line.endswith('mp3'):
tmpstr = line tmpstr = line
break break
if not len(tmpstr) > 1: if not tmpstr:
print('Could not find a mp3 stream') logging.getLogger(__name__).error('Could not find a mp3 stream')
sys.exit() sys.exit(1)
else: else:
streamurl = tmpstr streamurl = tmpstr
verboseprint(print_time() + " ... Stream URL: " + streamurl) verboseprint(print_time() + " ... Stream URL: " + streamurl)
target_dir = os.path.expandvars(settings['GLOBAL']['target_dir']) target_dir = os.path.expandvars(settings['GLOBAL']['target_dir'])
if not os.path.isdir(target_dir + os.sep): if not os.path.isdir(target_dir):
print('Target directory not found! Check that ' + target_dir + ' is a valid folder!') try:
sys.exit() os.mkdir(target_dir)
except FileNotFoundError:
logging.getLogger(__name__).error('Target directory not found! Check that ' +
target_dir + ' is a valid folder!')
sys.exit(1)
started_at = time.time() started_at = time.time()
should_end_at = started_at + (args.duration * 60) should_end_at = started_at + (args.duration * 60)
remaining = (args.duration * 60) remaining = (args.duration * 60)
@ -159,18 +169,20 @@ def record(args):
recthread = threading.Thread(target=record_worker, args=(stoprec, streamurl, target_dir, args)) recthread = threading.Thread(target=record_worker, args=(stoprec, streamurl, target_dir, args))
recthread.setDaemon(True) recthread.setDaemon(True)
recthread.start() recthread.start()
verboseprint(print_time() + " ... Started thread " + str(recthread) + " timeout: " + str(remaining / 60) + " min") verboseprint(print_time() + " ... Started thread " + str(recthread) + " timeout: " +
str(remaining / 60) + " min")
recthread.join(remaining) recthread.join(remaining)
verboseprint(print_time() + " ... Came out of rec thread again") verboseprint(print_time() + " ... Came out of rec thread again")
if(recthread.is_alive): if recthread.is_alive:
stoprec.set() stoprec.set()
verboseprint(print_time() + " ... Called stoprec.set()") verboseprint(print_time() + " ... Called stoprec.set()")
else: else:
verboseprint(print_time() + " ... recthread.is_alive = False") verboseprint(print_time() + " ... recthread.is_alive = False")
remaining = should_end_at - time.time() remaining = should_end_at - time.time()
verboseprint(print_time() + " ... Remaining: " + str(remaining / 60) + ", Threads: " + str(threading.activeCount())) verboseprint(print_time() + " ... Remaining: " + str(remaining / 60) +
", Threads: " + str(threading.activeCount()))
def list(args): def list(args):
@ -180,7 +192,8 @@ def list(args):
def main(): def main():
parser = argparse.ArgumentParser(description='This program records internet radio streams. It is free software and comes with ABSOLUTELY NO WARRANTY.') parser = argparse.ArgumentParser(description='This program records internet radio streams. '
'It is free software and comes with ABSOLUTELY NO WARRANTY.')
subparsers = parser.add_subparsers(help='sub-command help') subparsers = parser.add_subparsers(help='sub-command help')
parser_record = subparsers.add_parser('record', help='Record a station') parser_record = subparsers.add_parser('record', help='Record a station')
parser_record.add_argument('station', type=str, parser_record.add_argument('station', type=str,
@ -201,7 +214,8 @@ def main():
parser_record.set_defaults(func=record) parser_record.set_defaults(func=record)
parser_list = subparsers.add_parser('list', help='List all known stations') parser_list = subparsers.add_parser('list', help='List all known stations')
parser_list.set_defaults(func=list) parser_list.set_defaults(func=list)
parser_list.add_argument('-s', '--settings', nargs='?', type=str, help="specify alternative location for settings.ini") parser_list.add_argument('-s', '--settings', nargs='?', type=str,
help="specify alternative location for settings.ini")
if not len(sys.argv) > 1: if not len(sys.argv) > 1:
print('Error: No argument specified.\n') print('Error: No argument specified.\n')
@ -210,5 +224,6 @@ def main():
args = parser.parse_args() args = parser.parse_args()
args.func(args) args.func(args)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -8,7 +8,7 @@ dkultur = http://www.deutschlandradio.de/streaming/dkultur.m3u
dlf = http://www.deutschlandradio.de/streaming/dlf.m3u dlf = http://www.deutschlandradio.de/streaming/dlf.m3u
dwissen = http://dradio_mp3_dwissen_m.akacast.akamaistream.net/7/728/142684/v1/gnl.akacast.akamaistream.net/dradio_mp3_dwissen_m dwissen = http://dradio_mp3_dwissen_m.akacast.akamaistream.net/7/728/142684/v1/gnl.akacast.akamaistream.net/dradio_mp3_dwissen_m
erfplus = http://c14000-l.i.core.cdn.streamfarm.net/14000cina/live/3212erf_96/live_de_96.mp3 erfplus = http://c14000-l.i.core.cdn.streamfarm.net/14000cina/live/3212erf_96/live_de_96.mp3
mdrklassik = http://avw.mdr.de/livestreams/mdr_klassik_live_128.m3u mdrklassik = http://avw.mdr.de/streams/284350-0_mp3_high.m3u
radioeins = http://www.radioeins.de/live.m3u radioeins = http://www.radioeins.de/live.m3u
swr2 = http://mp3-live.swr.de/swr2_m.m3u swr2 = http://mp3-live.swr.de/swr2_m.m3u
wdr3 = http://wdr-wdr3-live.icecast.wdr.de/wdr/wdr3/live/mp3/256/stream.mp3 wdr3 = http://wdr-wdr3-live.icecast.wdr.de/wdr/wdr3/live/mp3/256/stream.mp3