I have class A which inheritance the class B
i need to send main_b to thread and continue with the program (main_a)
import threading
import time
class B(object):
def main_b(self):
i = 0
while i < 5:
print "main_b: %s" %time.ctime(time.time())
time.sleep(1)
i += 1
class A(B):
def main_a(self):
b = threading.Thread(target=self.main_b())
b.start()
i = 0
while i < 5:
print "main_a: %s" %time.ctime(time.time())
time.sleep(1)
i += 1
b.join()
aa = A()
aa.main_a()
Expected result main_b and main_a print at same time
Actual:
main_b: Thu Sep 22 09:57:44 2016
main_b: Thu Sep 22 09:57:45 2016
main_b: Thu Sep 22 09:57:46 2016
main_a: Thu Sep 22 09:57:47 2016
main_a: Thu Sep 22 09:57:48 2016
main_a: Thu Sep 22 09:57:49 2016
Just pass method as a target for thread:
b = threading.Thread(target=self.main_b)
Related
The function is passed a dictionary containing three lists with timestamps (time in seconds):
lesson - the beginning and end of the lesson
pupil - intervals of pupil presence
tutor - intervals of the teacher's presence
The intervals are arranged as follows - it is always a list of an even number of items. Even indices (starting from 0) are the time of entry to the lesson, and odd ones are the time of leaving the lesson.
How can I calculate the time when both student and teacher are present in class at the same time? That is, the time of their crossing
dc = {
'lesson': [1594663200, 1594666800],
'pupil': [1594663340, 1594663389, 1594663390, 1594663395, 1594663396, 1594666472],
'tutor': [1594663290, 1594663430, 1594663443, 1594666473]}
My solution, I could only calculate the total time spent by each
lesson_times = dc['lesson']
pupil_times = dc['pupil']
tutor_times = dc['tutor']
total_time_pupil = 0
start_time_pupil = 0
end_time_pupil = 0
if len(pupil_times) > len(tutor_times):
for index, times in pupil_times
for index, time in enumerate(pupil_times):
if (index % 2) == 0:
start_time_pupil = time
else:
end_time_pupil = time
if start_time_pupil != 0 and end_time_pupil !=0:
total_time_pupil += (end_time_pupil - start_time_pupil)
start_time_pupil = 0
end_time_pupil = 0
tutor_times = dc['tutor']
total_time_tutor = 0
start_time_tutor = 0
end_time_tutor = 0
for index, time in enumerate(tutor_times):
if (index % 2) == 0:
start_time_tutor = time
else:
end_time_tutor = time
if start_time_tutor != 0 and end_time_tutor != 0:
total_time_tutor += (end_time_tutor - start_time_tutor)
start_time_tutor = 0
end_time_tutor = 0
I had written this when you posted the first time. This solves your problem.
import time
dc = {
'lesson': [1594663200, 1594666800],
'pupil': [1594663340, 1594663389, 1594663390, 1594663395, 1594663396, 1594666472],
'tutor': [1594663290, 1594663430, 1594663443, 1594666473]}
puptimes = dc['pupil'][:]
tuttimes = dc['tutor'][:]
pupil_in = False
tutor_in = False
last = 0
together = 0
while puptimes and tuttimes:
# Pick the event to come next.
if puptimes[0] < tuttimes[0]:
evt = puptimes.pop(0)
pupil_in = not pupil_in
else:
evt = tuttimes.pop(0)
tutor_in = not tutor_in
tc = time.ctime(evt)
if pupil_in and tutor_in:
print( tc, "Both are in the room." )
last = evt
else:
if last:
print( tc, "No longer both in, together time =", evt-last )
together += evt-last
last = 0
if pupil_in:
print( tc, "Pupil is in the room alone" )
elif tutor_in:
print( tc, "Tutor is in the room alone" )
else:
print( tc, "Room is empty" )
print( "Total time together:", together, "seconds" )
Output:
[timr#Tims-Pro:~/src]$ python x.py
Mon Jul 13 11:01:30 2020 Tutor is in the room alone
Mon Jul 13 11:02:20 2020 Both are in the room.
Mon Jul 13 11:03:09 2020 No longer both in, together time = 49
Mon Jul 13 11:03:09 2020 Tutor is in the room alone
Mon Jul 13 11:03:10 2020 Both are in the room.
Mon Jul 13 11:03:15 2020 No longer both in, together time = 5
Mon Jul 13 11:03:15 2020 Tutor is in the room alone
Mon Jul 13 11:03:16 2020 Both are in the room.
Mon Jul 13 11:03:50 2020 No longer both in, together time = 34
Mon Jul 13 11:03:50 2020 Pupil is in the room alone
Mon Jul 13 11:04:03 2020 Both are in the room.
Mon Jul 13 11:54:32 2020 No longer both in, together time = 3029
Mon Jul 13 11:54:32 2020 Tutor is in the room alone
Total time together: 3117 seconds
[timr#Tims-Pro:~/src]$
I have a log file above
m = '''Jan 23 2010 10:30:08AM - abc def Server-1 connected
Jan 23 2010 11:04:56AM - abc def Server-2 connected
Jan 23 2010 1:18:32PM - abc def Server-2 disconnected from server
Jan 23 2010 4:16:09PM - abc def Aws activity from 10.0.0.45
Jan 23 2010 9:43:44PM - abc def Server-1 disconnected from server
Feb 1 2010 12:40:28AM - abc def Server-1 connected
Feb 1 2010 1:21:52AM - abc def Aws activity from 192.168.123.4
Mar 29 2010 1:13:07PM - def def Server-1 disconnected from server'''
My expected out
Server-1 - connected at 23/01/2016 10:30:08 and disconnected at 23/01/2016 21:43:44
Server-2 - connected at 23/01/2016 11:04:56 and disconnected at 23/01/2016 13:18:32
Aws - connected at 01/02/2016 12:40:28 and disconnected at 29/03/2016 13:13:07
My approach and code convert the file into dictionary and format
Pseudo code
import re
x = re.findall(r'(.*) - abc def (Server-1|Server-2) (connected|disconnected)',m)
y = re.findall(r'Aws activity from (\d.+)', m)
for i in x:
if i[2] == 'connected':
print (f'{i[1]} - connected at {i[0]} ' )
if i[2] == 'disconnected':
print (f'{i[1]} - disconnected at {i[0]} ' )
I have a read.log file that will have lines such as...
10.2.177.170 Tue Jun 19 03:30:55 CDT 2018
10.2.177.170 Tue Jun 19 03:31:03 CDT 2018
10.2.177.170 Tue Jun 19 03:31:04 CDT 2018
10.2.177.170 Tue Jun 19 03:32:04 CDT 2018
10.2.177.170 Tue Jun 19 03:33:04 CDT 2018
My code will read the 3rd to last line and combine strings. So the normal output would be:
2018:19:03:32:04
My problem is, if there are only 4 or less lines of data such as
10.1.177.170 Tue Jun 19 03:30:55 CDT 2018
10.1.177.170 Tue Jun 19 03:31:03 CDT 2018
10.1.177.170 Tue Jun 19 03:31:04 CDT 2018
10.1.177.170 Tue Jun 19 03:32:04 CDT 2018
I get an error
x1 = line.split()[0]
IndexError: list index out of range
How can I error check this or keep it from happening? I have been trying to check how many lines there are in the log and if less than 5, print a notice. Are there better options?
def run():
f = open('read.log', 'r')
lnumber = dict()
for num,line in enumerate(f,1):
x1 = line.split()[0]
log_day = line.split()[3]
log_time = line.split()[4]
log_year = line.split()[6]
if x1 in lnumber:
lnumber[x1].append((log_year + ":" + log_day + ":" + log_time))
else:
lnumber[x1] = [(num,log_time)]
if x1 in lnumber and len(lnumber.get(x1,None)) > 2:
# if there are less than 3 lines in document, this will fail
line_time = (lnumber[x1][-3].__str__())
print(line_time)
else:
print('nothing')
f.close
run()
f.readlines() gives you a list of lines in a file. So, you could try reading in all the lines in a file:
f = open('firewall.log', 'r')
lines = f.readlines()
And exiting if there are 4 or less lines:
if len(lines) <= 4:
f.close()
print("4 or less lines in file")
exit()
That IndexError you're getting is because you're calling split() on a line with nothing on it. I would suggest doing something like if not line: continue to avoid that case.
I am trying to create java jar with the files in AWS S3 by Lambda function using Python
I have tried in both ways
import os
def lambda_handler(event, context):
os.system('jar cf abc.jar, file1.txt, file2.txt')
return "Success"
and
import subprocess
def lambda_handler(event, context):
subprocess.call('jar cf abc.jar, file1.txt, file2.txt')
return "Success"
Remove commas
import subprocess
subprocess.call('jar cf abc.jar *.py')
# import os
# os.system('jar cf abc.jar *.py')
print("Done")
Output :
Done
Process finished with exit code 0
Verifying :
import subprocess
subprocess.call('jar tvf abc.jar')
# import os
# os.system('jar tvf abc.jar')
Output :
0 Wed Feb 28 18:22:32 IST 2018 META-INF/
68 Wed Feb 28 18:22:32 IST 2018 META-INF/MANIFEST.MF
196 Wed Jan 24 20:27:32 IST 2018 dirTut.py
438 Tue Jan 09 20:44:00 IST 2018 epochtodatetime.py
1540 Sun Jan 07 15:30:42 IST 2018 firstServer.py
164 Sun Jan 14 19:34:20 IST 2018 flaskTut.py
295 Tue Jan 09 17:59:20 IST 2018 funcOverriding.py
390 Tue Jan 09 16:55:24 IST 2018 underscore.py
I have a text file that is output from a command that I ran with Netmiko to retrieve data from a Cisco WLC of things that are causing interference on our WiFi network. I stripped out just what I needed from the original 600k lines of code down to a couple thousand lines like this:
AP Name.......................................... 010-HIGH-FL4-AP04
Microwave Oven 11 10 -59 Mon Dec 18 08:21:23 2017
WiMax Mobile 11 0 -84 Fri Dec 15 17:09:45 2017
WiMax Fixed 11 0 -68 Tue Dec 12 09:29:30 2017
AP Name.......................................... 010-2nd-AP04
Microwave Oven 11 10 -61 Sat Dec 16 11:20:36 2017
WiMax Fixed 11 0 -78 Mon Dec 11 12:33:10 2017
AP Name.......................................... 139-FL1-AP03
Microwave Oven 6 18 -51 Fri Dec 15 12:26:56 2017
AP Name.......................................... 010-HIGH-FL3-AP04
Microwave Oven 11 10 -55 Mon Dec 18 07:51:23 2017
WiMax Mobile 11 0 -83 Wed Dec 13 16:16:26 2017
The goal is to end up with a csv file that strips out the 'AP Name ...' and puts what left on the same line as the rest of the information in the next line. The problem is some have two lines below the AP name and some have 1 or none. I have been at it for 8 hours and cannot find the best way to make this happen.
This is the latest version of code that I was trying to use, any suggestions for making this work? I just want something I can load up in excel and create a report with:
with open(outfile_name, 'w') as out_file:
with open('wlc-interference_raw.txt', 'r')as in_file:
#Variables
_ap_name = ''
_temp = ''
_flag = False
for i in in_file:
if 'AP Name' in i:
#write whatever was put in the temp file to disk because new ap now
#add another temp variable in case an ap has more than 1 interferer and check if new AP name
out_file.write(_temp)
out_file.write('\n')
#print(_temp)
_ap_name = i.lstrip('AP Name.......................................... ')
_ap_name = _ap_name.rstrip('\n')
_temp = _ap_name
#print(_temp)
elif '----' in i:
pass
elif 'Class Type' in i:
pass
else:
line_split = i.split()
for x in line_split:
_temp += ','
_temp += x
_temp += '\n'
I think your best option is to read all lines of the file, then split into sections starting with AP Name. Then you can work on parsing each section.
Example
s = """AP Name.......................................... 010-HIGH-FL4-AP04
Microwave Oven 11 10 -59 Mon Dec 18 08:21:23 2017
WiMax Mobile 11 0 -84 Fri Dec 15 17:09:45 2017
WiMax Fixed 11 0 -68 Tue Dec 12 09:29:30 2017
AP Name.......................................... 010-2nd-AP04
Microwave Oven 11 10 -61 Sat Dec 16 11:20:36 2017
WiMax Fixed 11 0 -78 Mon Dec 11 12:33:10 2017
AP Name.......................................... 139-FL1-AP03
Microwave Oven 6 18 -51 Fri Dec 15 12:26:56 2017
AP Name.......................................... 010-HIGH-FL3-AP04
Microwave Oven 11 10 -55 Mon Dec 18 07:51:23 2017
WiMax Mobile 11 0 -83 Wed Dec 13 16:16:26 2017"""
import re
class AP:
"""
A class holding each section of the parsed file
"""
def __init__(self):
self.header = ""
self.content = []
sections = []
section = None
for line in s.split('\n'): # Or 'for line in file:'
# Starting new section
if line.startswith('AP Name'):
# If previously had a section, add to list
if section is not None:
sections.append(section)
section = AP()
section.header = line
else:
if section is not None:
section.content.append(line)
sections.append(section) # Add last section outside of loop
for section in sections:
ap_name = section.header.lstrip("AP Name.") # lstrip takes all the characters given, not a literal string
for line in section.content:
print(ap_name + ",", end="")
# You can extract the date separately, if needed
# Splitting on more than one space using a regex
line = ",".join(re.split(r'\s\s+', line))
print(line.rstrip(',')) # Remove trailing comma from imperfect split
Output
010-HIGH-FL4-AP04,Microwave Oven,11,10,-59,Mon Dec 18 08:21:23 2017
010-HIGH-FL4-AP04,WiMax Mobile,11,0,-84,Fri Dec 15 17:09:45 2017
010-HIGH-FL4-AP04,WiMax Fixed,11,0,-68,Tue Dec 12 09:29:30 2017
010-2nd-AP04,Microwave Oven,11,10,-61,Sat Dec 16 11:20:36 2017
010-2nd-AP04,WiMax Fixed,11,0,-78,Mon Dec 11 12:33:10 2017
139-FL1-AP03,Microwave Oven,6,18,-51,Fri Dec 15 12:26:56 2017
010-HIGH-FL3-AP04,Microwave Oven,11,10,-55,Mon Dec 18 07:51:23 2017
010-HIGH-FL3-AP04,WiMax Mobile,11,0,-83,Wed Dec 13 16:16:26 2017
Tip:
You don't need Python to write the CSV, you can output to a file using the command line
python script.py > output.csv