/
f.py
1962 lines (1542 loc) · 56.1 KB
/
f.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
import csv
import inspect
import math
import os
import random
import re
import socket
import string
import struct
import subprocess
import sys
import time
import urllib
import webbrowser
from datetime import datetime
from time import gmtime, strftime, localtime
import easygui
from selenium import webdriver
#############################################################
if os.name == 'nt': # Windows
import winsound
class Bcolors:
red = '\033[91m'
FAIL = '\033[91m'
green = '\033[92m'
PASS = '\033[92m'
yellow = '\033[93m'
WARN = '\033[93m'
WARNING = '\033[93m'
blue = '\033[94m'
purple = '\033[95m'
magenta = '\033[95m'
HEADER = '\033[95m'
cyan = '\033[96m'
ENDC = '\033[0m' # finish color
BOLD = '\033[1m' # no color
UNDERLINE = '\033[4m' # underline
class Pathes:
custom_report = r"E:\ME\USER\Steffen\rms_files\report\custom_report.html"
wkhtmltopdf = r"C:/Program Files/wkhtmltopdf/bin"
path_f_py = r"/home/kame/Dropbox/code/python/f.py"
# dropbox_path = "/home/kame/Dropbox/code/python/f.py"
# dropbox_path = "C:/users/steffen.schneider/Dropbox/code/python/f.py"
if os.name == 'posix':
main_lex = r"/home/kame/Dropbox/main-lex.txt"
main_lex_work = r"/home/kame/Dropbox/main-lex-work.txt"
diary = r"/home/kame/Desktop/main/diary.txt"
elif os.name == 'nt':
main_lex = "C:/Users/steffen.schneider/dropbox/main-lex.txt"
main_lex_work = "C:/Users/steffen.schneider/dropbox/main-lex-work.txt"
testfile = r"/home/kame/Desktop/testfile.txt"
todo_privat = r"/home/kame/Dropbox/TODO_privat.txt"
statistik_privat = r"/home/kame/Desktop/main/wichtig/ods/stats.xlsx"
wikipedia_categories = r"/home/kame/Dropbox/data/wikipedia_categories.txt"
##########
##########
# START
##########
##########
def analyse_element(self, xpath):
elements = self._driver.find_elements_by_xpath(xpath)
print("innerHTML of xpath: " + Bcolors.blue + str(xpath) + Bcolors.ENDC)
for element in elements:
print(element.get_attribute('innerHTML'))
print("outerHTML of xpath: " + Bcolors.blue + str(xpath) + Bcolors.ENDC)
for element in elements:
print(element.get_attribute('outerHTML'))
print("text of xpath: " + Bcolors.blue + str(xpath) + Bcolors.ENDC)
for element in elements:
print(element.text)
print("\n")
def battery():
get_battery_status_in_percent()
def binary_to_string(binary_string):
result = binary_string.decode('UTF-8')
return result
def change_dir(path):
os.chdir(path)
def check_if_odd(n):
return n % 2 == 1
def check_if_root():
if os.geteuid() == 0:
return True
else:
return False
def check_sleeping_time():
hour = int(strftime("%H", localtime()))
if hour >= 22:
print("It's late! Shut down your computer!!!!!")
def check_wlan():
url = "http://www.google.de"
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request(url)
try:
response = urlopen(req)
except HTTPError as e:
print('The server couldn\'t fulfill the request.')
print('Error code: ', e.code)
return False
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
return False
else:
# everything is fine
return True
def cli_progress(actual_val, end_val, bar_length=20):
percent = float(actual_val) / end_val
hashes = '#' * int(round(percent * bar_length))
spaces = '-' * (bar_length - len(hashes))
print("\rPercent: [{0}] {1}%".format(hashes + spaces, int(round(percent * 100))))
def close_process(process):
os.system("killall -9 " + str(process))
print("Process killed")
def com_port_read():
import serial
with serial.Serial('/dev/ttyS1', 19200, timeout=1) as ser:
x = ser.read() # read one byte
s = ser.read(10) # read up to ten bytes (timeout)
line = ser.readline() # read a '\n' terminated line
def com_port_write():
import serial
ser = serial.Serial('/dev/ttyUSB0') # open serial port
print(ser.name) # check which port was really used
ser.write(b'hello') # write a string
ser.close() # close port
def count_functions_in_fpy():
import re
dropbox_path = get_dropbox_home()
lst = []
# works under linux
for line in open(os.path.join(dropbox_path, 'code', 'python', 'f.py')):
# count the word def in this file
# don't count the word def in this function more than once
lst += re.findall(r'def ([a-z]){3,}', line)
print(str(len(lst)) + " functions available in f.py")
def create_dir_if_not_exists(directory):
if not is_dir_available(directory):
os.makedirs(directory)
def date_in_the_future(date):
# date-input: 20.12.2016
import datetime
from time import strptime
datetime_string = strptime(date, "%d.%m.%Y")
d = datetime.datetime(datetime_string[0], datetime_string[1], datetime_string[2])
now = datetime.datetime.now()
delta = d - now
diff = delta.days + 1
if diff > 0:
return True
else:
return False
def datetime_is_younger_than_other_datetime(date1, format1, date2, format2):
from datetime import datetime
from time import strptime
from time import mktime
if format1 is 'german':
format1 = "%d.%m.%Y %H:%M:%S"
elif format1 is 'american':
format1 = "%Y-%m-%d %H:%M:%S"
datetime_string1 = strptime(date1, format1) # parse to time.struct_time
datetime_string1 = datetime.fromtimestamp(mktime(datetime_string1))
if format2 is 'german':
format2 = "%d.%m.%Y %H:%M:%S"
elif format2 is 'american':
format2 = "%Y-%m-%d %H:%M:%S"
datetime_string2 = strptime(date2, format2) # parse to time.struct_time
datetime_string2 = datetime.fromtimestamp(mktime(datetime_string2))
return datetime_string1 > datetime_string2
def datetime_to_seconds(mydate):
result = re.match(r"\d\d\.\d\d\.\d\d\d\d \d\d:\d\d:\d\d", mydate)
if result is not None:
d = datetime.strptime(mydate, "%d.%m.%Y %H:%M:%S")
result = time.mktime(d.timetuple())
return result
result = re.match(r"\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d.\d\d\d", mydate)
if result is not None:
d = datetime.strptime(mydate, "%Y-%m-%d %H:%M:%S.%f")
result = time.mktime(d.timetuple())
return result
result = re.match(r"\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d", mydate)
if result is not None:
d = datetime.strptime(mydate, "%Y-%m-%d %H:%M:%S")
result = time.mktime(d.timetuple())
return result
def delete_chrome_history():
# SQLite3 database
# /home/kame/.config/chromium/Default/History
raise Exception("Not implemented yet")
def delete_duplicates_in_list(lst):
result = list(set(lst))
return result
def detect_devices():
import subprocess
df = subprocess.check_output("lsusb", shell=True)
devices = []
for i in df.decode('UTF-8').split('\n'):
devices.append(i)
return devices
def download_mp3_to_dropbox(url):
import urllib
# url = "http://podcast-mp3.dradio.de/podcast/2016/03/07/dlf_20160307_1949_c03fc129.mp3"
dropbox_path = get_dropbox_home()
path = dropbox_path + "/new_podcasts/"
urllib.request.urlretrieve(url, path + str(url[-30:]))
def file_count_lines(path):
with open(path, 'r') as fin:
a = fin.readlines()
return len(a)
def file_delete_duplicate_lines(path):
lst = file_to_list(path)
lst_2 = delete_duplicates_in_list(lst)
list_to_file(path, lst_2)
def file_delete_empty_lines(file_in):
with open(file_in, 'r') as fin:
data = ("".join(line for line in fin if not line.isspace()))
with open(file_in, 'w') as fout:
fout.writelines(data)
def file_delete_first_line(file_in):
with open(file_in, 'r') as fin:
data = fin.read().splitlines(True)
with open(file_in, 'w') as fout:
fout.writelines(data[1:])
def file_delete_lines_with_entry(file_in, entry):
f = open(file_in, "r+")
d = f.readlines()
f.seek(0)
for i in d:
if entry in i:
pass
else:
f.write(i)
f.truncate()
f.close()
def file_get_last_line(file_):
myarr = []
file_input = open(file_)
text = file_input.readlines() # .read() reads only one line
for line in text:
myarr.append(line)
return myarr[-1:][0][:-1]
def file_get_string(path):
mystring = ""
with open(path) as f:
contents = f.readlines()
for elem in contents:
mystring += str(elem)
return mystring
def file_get_text_from_file(path):
myarr = []
file_input = open(path)
text = file_input.readlines() # .read() reads only one line
for line in text:
myarr.append(line)
return myarr
def file_insert_line(path, index, value):
f = open(path, "r+")
data = f.readlines()
data.insert(index, value)
f.seek(0)
data = "".join(data)
f.write(data)
f.truncate()
f.close()
def file_replace_words(file_in, word_to_replace, replace_with):
f = open(file_in, "r+", encoding='utf8')
data = f.readlines()
f.seek(0)
for line in data:
line = re.sub(word_to_replace, replace_with, line)
f.write(line)
f.truncate()
f.close()
def file_sort_lines(path):
lst = file_to_list(path)
sorted_list = sorted(lst)
list_to_file(path, sorted_list)
def file_to_list(path):
with open(path) as f:
contents = f.readlines()
return contents
def file_word_analysis(path):
from collections import Counter
file = open(path, "r")
lines = file.readlines()
words = [word.lower() for line in lines for word in line.split()]
list2 = []
for word in words:
word = re.sub("\.", "", word)
word = re.sub("-", "", word)
word = re.sub("\(", "", word)
word = re.sub("\)", "", word)
word = re.sub("\?", "", word)
word = re.sub("\!", "", word)
word = re.sub("#", "", word)
word = re.sub("\[", "", word)
word = re.sub("\]", "", word)
word = re.sub(",", "", word)
word = re.sub("\"", "", word)
word = re.sub("\'", "", word)
word = re.sub(":", "", word)
word = re.sub(";", "", word)
word = re.sub("\/", " ", word)
list2.append(word)
wordcount = Counter(list2)
for item in sorted(wordcount.items(), key=lambda l: l[1], reverse=True): print("{}\t{}".format(*item))
def get_battery_status_in_percent():
if os.name == 'posix':
path = "/sys/class/power_supply/BAT0/energy_now"
if is_dir_available(path):
pass
else:
path = "/sys/class/power_supply/BAT0/charge_now"
now_ = open(path).read()
# print("now: " + str(now_))
path = "/sys/class/power_supply/BAT0/energy_full"
if is_dir_available(path):
pass
else:
path = "/sys/class/power_supply/BAT0/charge_full"
full_ = open(path).read()
# print("full: " + str(full_))
result = 100.0 * int(now_) / int(full_)
result = str("{0:.1f}".format(result))
# print("battery: " + result + " %")
if float(result) < 20.0:
print("###########################################")
print("###########################################")
print("######### low - battery #########")
print("###########################################")
print("###########################################")
return result
def get_computer_name():
print("Computer name: " + str(socket.gethostname()))
def get_current_path():
result = os.getcwd()
return result
def get_date():
date = strftime("%d.%m.%Y", localtime()) # local time
return date
def get_datetime():
datetime_ = strftime("%d.%m.%Y %H:%M:%S", localtime()) # local time
return datetime_
def get_datetime_plus_two_minutes():
ts = get_seconds_since_1970_with_microseconds()
ts2 = ts + 120
datetime_ = strftime('%Y-%m-%d %H:%M:%S', localtime(ts2))
return datetime_
def get_day_of_the_year():
result = datetime.now().timetuple().tm_yday
# print(result)
return result
def get_dropbox_home():
from platform import system
import base64
import os.path
_system = system()
if _system in ('Windows', 'cli'):
host_db_path = os.path.join(get_local_appdata_path(),
'Dropbox',
'host.db')
elif _system in ('Linux', 'Darwin'):
host_db_path = os.path.expanduser('~'
'/.dropbox'
'/host.db')
else:
raise RuntimeError('Unknown system={}'
.format(_system))
if not os.path.exists(host_db_path):
raise RuntimeError("Config path={} doesn't exists"
.format(host_db_path))
with open(host_db_path, 'r') as f:
data = f.read().split()
return base64.b64decode(data[1]).decode('ascii')
def get_filenames_from_dir(path):
import glob
path += "*.mp3"
return glob.glob(path)
def get_id_tags(url):
# check link syntax
if url[:4] != 'http' and url[:3] != 'www':
url = 'http://www.' + str(url)
if url[:4] != 'http':
url = 'http://' + str(url)
if url[-1:] != '/':
url += '/'
# get content
content_ = urllib.request.urlopen(url).read()
items = re.findall(r'id=\"(.*?)\"', str(content_))
return items
def get_installed_modules():
import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s" % i.key for i in installed_packages])
return installed_packages_list
def get_links(url):
# example link
# url = 'http://www.heise.de/'
# check link syntax
if url[:4] != 'http' and url[:3] != 'www':
url = 'http://www.' + str(url)
if url[:4] != 'http':
url = 'http://' + str(url)
if url[-1:] != '/':
url += '/'
# get content
content_ = urllib.request.urlopen(url).read()
# search for "a href"
items = re.findall("<a href=\"(.+\.html)\"", content_) # get links with ending .html
# delete duplicates
lst = list(set(list(items)))
# return links
for i in range(len(lst)):
if lst[i][:4] != 'http':
lst[i] = url + str(lst[i][1:])
return lst
def get_local_appdata_path():
path = os.getenv('LOCALAPPDATA')
return path
def get_local_time():
time_now = strftime("%H:%M:%S", localtime()) # local time
return time_now
def get_mac():
from uuid import getnode as get_mac_
mac = get_mac_()
return mac
def get_minute_of_the_day():
hour = strftime("%H", localtime())
minute = strftime("%M", localtime())
minute_of_the_day = int(hour) * 60 + int(minute)
return str(minute_of_the_day)
def get_mod():
result = get_minute_of_the_day()
return result
def get_mousepos():
curr = subprocess.check_output(["xdotool", "getmouselocation"]).decode("utf-8")
return [int(it.split(":")[1]) for it in curr.split()[:2]]
def get_my_ip():
# myip = socket.gethostbyname(socket.gethostname())
if get_my_os() == 'linux':
myip = os.system("ifconfig | awk '/inet addr/{print substr($2,6)}'")
myip_deutsch = os.system("ifconfig | awk '/inet Adresse:/{print substr($3,7)}'")
if len(str(myip)) < 2:
print(myip_deutsch)
else:
print(myip)
return myip
else:
hostname = socket.gethostname()
myip = socket.gethostbyname(hostname)
print(myip)
return myip
# or
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# s.connect(("8.8.8.8", 80))
# return s.getsockname()[0]
def get_my_os():
get_os_name()
def get_news():
if check_wlan():
from pyvirtualdisplay import Display
import re
display = Display(visible=0, size=(800, 600))
display.start()
driver = webdriver.Firefox()
url = "http://www.deutschlandfunk.de/"
driver.get(url)
source = driver.find_element_by_xpath('//*[@id="wrapper"]/div/section[2]/div[1]').get_attribute('innerHTML')
n_articles = source.count('<article')
print(str(n_articles) + " articles found.")
lst = re.findall('<h3>(.+)</h3>', source)
result = lst
driver.close()
display.stop()
return result
else:
print("Error: Not connected to the internet")
def get_nth_line(path, linenumber):
# starts at 1 !!!
import linecache
return linecache.getline(path, linenumber)
def get_os_name():
""" e.g. posix, nt """
result = os.name
if result == 'posix':
return 'linux'
elif result == 'nt':
return 'windows'
else:
return 'unknown system'
def get_python_version():
print(sys.version)
def get_script_path():
result = os.path.dirname(os.path.abspath(__file__))
return result
def get_second():
time_now = strftime("%S", localtime())
return time_now
def get_seconds_since_1970_with_microseconds():
import time
ts = time.time()
return ts
def get_seconds_since_1970_without_microseconds():
import time
import math
ts = time.time()
ts = math.floor(ts)
return ts
def get_temperature():
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
driver = webdriver.Firefox()
url = "http://www.yr.no/sted/Tyskland/Baden-W%C3%BCrttemberg/Bad_S%C3%" \
"A4ckingen/time_for_time.html"
driver.get(url)
result = driver.find_element_by_xpath('//*[@id="ctl00_ctl00_contentBody"]/div[2]/div[3]/table[1]/tbody/tr[1]/td['
'3]').get_attribute('innerHTML')
result = result[:-1] # don't show degree sign
driver.close()
display.stop()
print("It is " + result + " degrees.")
return result
def get_time():
time_ = get_local_time()
return time_
def get_todo():
path = Pathes.todo_privat
print("Tasks from " + str(path) + ": ")
with open(path) as f:
reader = csv.DictReader(f)
for row in reader:
print('{:.<41} {}'.format(row['TASK'], row['DATE']))
def get_todo_without_future():
path = Pathes.todo_privat
print("Tasks from " + str(path) + ": ")
with open(path) as file_:
for row in file_:
date = re.findall(r"\d+\.\d+\.\d+", row)[0]
if not date_in_the_future(str(date)):
string = row[:-1]
print(string.split('\t')[0] + "\t" + string.split('\t')[1])
def get_top():
"""show cpu most consuming processes"""
print("This processes are using the cpu the most:")
print(os.system("ps axo %cpu,pid,euser,cmd | sort -nr | head -n 5"))
def get_utc_time():
time_now = strftime("%H:%M:%S", gmtime()) # utc
return time_now
def get_weekday():
"""
0 --> Monday
6 --> Sunday
I will add 1
1 --> Monday
7 --> Sunday
"""
result = datetime.today().weekday() + 1
return result
def html_analyse_element(self, xpath):
print(Bcolors.cyan + re.findall(r".*\\(.*)", inspect.stack()[0][1])[0] + " --- " + inspect.stack()[0][
3] + "()" + Bcolors.ENDC)
elements = self._driver.find_elements_by_xpath(xpath)
print("innerHTML of xpath: " + Bcolors.blue + str(xpath) + Bcolors.ENDC)
for element in elements:
print(element.get_attribute('innerHTML'))
print("outerHTML of xpath: " + Bcolors.blue + str(xpath) + Bcolors.ENDC)
for element in elements:
print(element.get_attribute('outerHTML'))
print("text of xpath: " + Bcolors.blue + str(xpath) + Bcolors.ENDC)
for element in elements:
print(element.text)
print("\n")
def html_open_random_bookmarks_chromium(n=5):
file_ = "/home/kame/.config/chromium/Default/Bookmarks"
file_input = open(file_, "r")
text = file_input.readlines() # .read() read only one line
count = 0
for line in text:
if '"url":' in line:
count += 1
for i in range(n):
# choose random bookmark
rnd = random.randint(0, count - 1)
count = 0
line_with_link = ""
for line in text:
if '"url":' in line:
if count == rnd:
line_with_link = line
count += 1
# todo - sometimes not working
url = re.findall(r"url.*\"(.*)\"", line_with_link)[0]
webbrowser.open(url, new=2) # open in a new tab, if possible
def html_open_random_bookmarks_from_xmlfile():
"""
Open random links from my bookmark.xml
example of xml:
<mylinks>
<item>
<name>Python3 - library</name>
<url>https://docs.python.org/3/library/index.html</url>
<category>python</category>
<active>true</active> # show page only if true
<frequency>5</frequency> # 1 call it less often; 9 --> call it most often
</item>
</mylinks>
"""
import random
import re
import time
import webbrowser
# get input
myhtml = r"/home/kame/Dropbox/data/links.xml"
file_input = open(myhtml)
xml = file_input.readlines()
# create 2d array
lst = []
row = 0
# xml to 2d list
for i in range(len(xml)):
# new item
# create new row
if xml[i].strip()[:5] == '<item':
# print("new item found")
lst.append([])
if xml[i].strip()[:5] == '<name':
item = re.findall("<name>(.+)</name>", xml[i])
try:
lst[row].append(item[0])
except RuntimeError:
pass
if xml[i].strip()[:5] == '<url>':
item = re.findall("<url>(.+)</url>", xml[i])
try:
lst[row].append(item[0])
except RuntimeError:
pass
if xml[i].strip()[:5] == '<cate':
item = re.findall("<category>(.+)</category>", xml[i])
try:
lst[row].append(item[0])
except RuntimeError:
pass
if xml[i].strip()[:5] == '<acti':
item = re.findall("<active>(.+)</active>", xml[i])
try:
lst[row].append(item[0])
except RuntimeError:
pass
if xml[i].strip()[:5] == '<freq':
item = re.findall("<frequency>(.+)</frequency>", xml[i])
try:
lst[row].append(item[0])
except RuntimeError:
pass
if xml[i].strip()[:5] == '</ite':
# print("item finished")
row += 1
print(lst)
# choose category
categories = []
for i in range(row):
try:
categories.append(lst[i][2])
except RuntimeError:
pass
# todo - choose category
print("all categories:")
# show unique values
print(sorted(set(categories)))
count = 0
for i in range(30):
try:
rnd = random.randint(0, row)
rnd_2 = random.randint(0, 9)
# check if is active
if 'false' in lst[rnd][3]:
pass
if 'true' in lst[rnd][3]:
if int(lst[rnd][4]) > int(rnd_2): # regard the frequency
url = lst[rnd][1]
print("url: " + str(url))
if url[0:4] != 'http':
url = 'http://' + str(url)
webbrowser.open(url, new=2) # open in a new tab, if possible
count += 1
time.sleep(3)
if count == 5:
break
else:
continue
except RuntimeError:
pass
# print("xml field empty")
def html_open_random_wikipedia(n=2, m=4):
# get categories from txt-file (dropbox/data/wikipedia_categories)
categories = []
path = Pathes.wikipedia_categories
with open(path) as file:
for row in file:
if "ausgeschaltet" in row:
pass
else:
categories.append(row.split('\t')[-1][:-1])
categories = ' '.join(categories).split()
for i in range(n):
rnd = random.randint(0, len(categories) - 1)
print(categories[rnd])
for j in range(m):
time.sleep(1)
url = "https://de.wikipedia.org/wiki/Spezial:Zuf%C3%A4llig_in_Kategorie/" + str(categories[rnd])
webbrowser.open(url, new=2) # open in a new tab, if possible
def html_to_pdf(input_file, output_file):
print(Bcolors.cyan + re.findall(r".*\\(.*)", inspect.stack()[0][1])[0] + " --- " + inspect.stack()[0][
3] + "()" + Bcolors.ENDC)
if "\\" in output_file:
pass
else:
output_file = r"C:\Users\Steffen.schneider\Desktop\\" + str(output_file)
get_os_name()
path = Pathes.wkhtmltopdf
assert os.path.exists(path), "wkhtmltopdf doesn't exist. Please install"
change_dir(path)
get_current_path()
os.system("wkhtmltopdf " + str(input_file) + " " + str(output_file))
def install_easygui():
# windows
if os.name == 'nt':
os.system("py -2 -m pip install easygui --trusted-host pypi.python.org")
os.system("py -3 -m pip install easygui --trusted-host pypi.python.org")
if os.name == 'posix':
sudo_password = input("sudo password: ")
command = 'sudo -H pip install easygui'
os.system('echo %s|sudo -S %s' % (sudo_password, command))
def install_ipython():
print("You have to set the correct python path")
print(r"set PATH = % PATH %; C:\Users\steffen.schneider\AppData\Local\Programs\Python\Python35-32\Scripts")
os.system("py -3 -m pip install ipython --trusted-host pypi.python.org")
def install_numpy():
if python_32_or_64_bit() == '32':
print("download from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy")
print("pip install xxxxx.whl")
elif python_32_or_64_bit() == '64':
os.system("py -2 -m pip install numpy --trusted-host pypi.python.org")
os.system("py -3 -m pip install numpy --trusted-host pypi.python.org")
else:
print("python_32_or_64_bit() isn't working correct")
def install_pcap():
os.system("py -2 -m pip install pypcap --trusted-host pypi.python.org")
def install_pdfminer():
os.system("py -3 -m pip install pdfminer3k --trusted-host pypi.python.org")
def install_pillow():
os.system("py -2 -m pip install pillow --trusted-host pypi.python.org")
os.system("py -3 -m pip install pillow --trusted-host pypi.python.org")
def install_pyautoit():
os.system("py -2 -m pip install pyautoit --trusted-host pypi.python.org")
os.system("py -3 -m pip install pyautoit --trusted-host pypi.python.org")
def install_pymodbus3():
# version for python2 ???
os.system("py -3 -m pip install pymodbus3 --trusted-host pypi.python.org")
def install_pymouse():
os.system("py -2 -m pip install pymouse --trusted-host pypi.python.org")
os.system("py -3 -m pip install pymouse --trusted-host pypi.python.org")
def install_pymysql():
os.system("py -2 -m pip install pymysql --trusted-host pypi.python.org")
os.system("py -3 -m pip install pymysql --trusted-host pypi.python.org")
def install_pywin32():
os.system("py -2 -m pip install pypiwin32 --trusted-host pypi.python.org")
os.system("py -3 -m pip install pypiwin32 --trusted-host pypi.python.org")