Python 3: time.tzset() alternative for Windows? - python-3.x

I am new to Python. I am reading about dates and times from the lovely book 'Python 3 Standard Library by Example' by Doug Hellmann and I stumbled upon this code snippet:
import time
import os
def show_zone_info():
print(f'''\
TZ : {os.environ.get('TZ', '(not set)')}
tzname: {time.tzname}
Zone : {time.timezone} ({time.timezone / 3600})
DST : {time.daylight}
Time : {time.ctime()}
''')
if __name__ == '__main__':
print('Default: ')
show_zone_info()
ZONES = [
'GMT',
'Europe/Amsterdam'
]
for zone in ZONES:
os.environ['TZ'] = zone
# time.tzset() # Only available on Unix
print(zone, ':')
show_zone_info()
Problem is, time.tzset() is only available on Unix and without it on Windows machine, timezone doesn't change during the run time of the code. What is the alternative to time.tzset() on Windows? (I am running Python 3.8.3 on Windows 10 at the time of asking this question.)

Related

SyntaxError when using print(""" with a lst of numbers to populate a file with GROMACS patched with PLUMED

I am using GROMACS with PLUMED to run MD simulations. In setting up my plumed file for collecting the S2/SH CV from Omar(https://www.plumed.org/doc-v2.8/user-doc/html/_s2_c_m.html) I am having difficulties with the line:
File "makingplumed.py", line 25
""" % (x,i)file=f)
^
SyntaxError: invalid syntax
Here is the code I am trying to run:
# here we create the PLUMED input file with python
with open("plumed.dat","w") as f:
# print initial stuff
#K# from __future__ import print_function
# Define Atoms which are Oxygen hydrogen bond acceptors
ATOMS=[21,35,45,62,76,97,109,133,152,174,188,202,213,227,239,253,269,280,292,311,323,339,353,377,401,416,426,447,466,477,488,503,518,538,560,575,597,617,624,641,655,677,692,702,722,743,765,784,798,820,844,866,883,897,919,939,961,978,988,1004,1021,1040]
#Define heavy atoms for S2CM CV (protein and backbone and not hydrogen)
heavy_atoms_nh: GROUP ATOMS=1,5,7,10,12,16,20,21,22,23,26,29,32,34,35,36,38,40,44,45,46,48,50,53,54,55,57,59,61,62,63,64,67,70,73,75,76,79,81,84,85,87,89,90,92,94,96,97,98,100,102,105,106,107,108,109,110,112,114,117,120,123,124,125,126,129,132,133,134,136,138,141,143,147,151,152,153,155,157,160,163,166,169,173,174,175,177,179,181,185,187,188,189,191,193,195,199,201,202,203,205,207,210,212,213,214,216,217,218,220,224,226,227,228,230,232,235,236,237,238,239,240,241,244,247,250,252,253,254,256,258,260,264,268,269,270,272,274,277,279,280,281,283,285,288,291,392,293,295,297,299,303,306,310,311,312,314,316,319,320,321,322,323,326,328,330,334,338,339,340,342,344,346,350,352,353,354,356,358,361,364,367,369,370,373,376,377,378,380,382,385,388,391,393,397,400,401,402,404,406,409,412,415,416,417,419,421,425,426,427,429,431,434,345,437,439,442,444,446,447,448,450,452,455,457,461,465,466,467,469,471,474,476,477,478,480,482,485,487,489,491,493,496,499,500,501,502,503,504,506,508,511,514,515,516,517,518,519,521,523,526,527,529,531,533,535,537,538,539,541,543,546,549,552,555,559,560,561,563,265,268,571,572,573,574,575,576,578,580,583,586,589,592,596,597,598,600,602,605,606,608,610,612,614,616,617,618,620,623,624,625,627,629,632,635,636,640,641,642,644,646,648,652,654,655,656,658,660,663,666,669,672,676,677,678,680,682,685,688,691,692,693,695,697,701,702,703,705,707,710,711,713,715,717,719,721,722,723,725,727,730,731,733,735,738,740,742,743,744,746,748,751,754,757,760,764,765,766,768,770,773,775,779,783,784,785,786,789,792,795,797,798,799,801,803,806,809,812,815,819,820,821,823,825,828,829,831,833,834,836,838,840,842,843,844,845,847,849,852,855,858,861,865,866,867,869,871,874,877,878,879,882,883,884,886,888,891,892,893,896,867,898,900,902,905,908,911,914,918,919,920,922,924,927,928,930,932,934,936,938,939,940,942,944,947,950,953,956,960,961,962,964,966,969,975,973,977,978,979,981,983,987,988,989,991,993,995,999,1003,1004,1005,1007,1009,1012,1015,1016,1017,1020,1021,1022,1024,1026,1029,1031,1035,1039,1040,1041,1043,1045,1048,1049,1051,1053,1055,1057,1059,1060,1061
for x in range(len(ATOMS)):
for i in range(1, 60):
print("""
S2CM ...
NH_ATOMS=x,x+2
HEAVY_ATOMS=heavy_atoms_nh
LABEL=S2nh-%d
R_EFF=0.10
PREFACTOR_A=0.80
EXPONENT_B=1.0
OFFSET_C=0.10
N_I=1
NOPBC
... S2CM
""" % (x,i)file=f)
I am just learning python and Linux this summer as I am getting involved with computational biochemistry research, so if there is a simple fix I am very sorry for the waste of time, and I appreciate any and all time and attention to this matter.
python3 --version
Python 3.6.13
Thank You,
David Cummins
Masters Student at Western Washington University

I am not able to call one python script from another script using os.system in Pycharm

My sample file in one project is:
import os
feature_name = 'neelam'
combo_boxes = {"'Primary CAN InterfaceComboBox": ["[CanSim, CanSim]", "best_match"],
"'Secondary CAN InterfaceComboBox": ["[CanSim, CanSim]", "best_match"],
"Seed Data SimulationComboBox": ["[Off, OFF]", "best_match"],
"Planter TypeComboBox": ["[_2160_FFT_24R30, 2160 Front Fold 24 Row 30 Inch]", "best_match"],
"BrandComboBox": ["[CaseIH, Case IH]", "best_match"],
"LATAM Gran Fertilizer InstalledComboBox": ["[Hydraulic, Hydraulic]", "best_match"],
"DiagnosticsComboBox": ["[On, ON]", "best_match"]}
for i in combo_boxes:
log_msg = 'Click on combo box {0} at {1}'.format(i, combo_boxes[i][0].split(",")[1][:-1])
print(log_msg)
Now I am trying to run sample file from another python script as given:
import os
script_string = r'C:\Neelam\Neelam_Dev\test_automation\FeatureTestScripts\Common\sample.py'
os.system(script_string)
But after running the second file, it is not printing the output of sample.py. It is just opening that file in Pycharm.

tkinter animation speed on windows and linux

I was trying to create simple 2d game using tkinter, but faced with interesting problem: animation speed is quite different on various computers.
To test this, I've create script, that measures time of animation
import tkinter as tk
import datetime
root = tk.Tk()
can = tk.Canvas(height=500, width=1000)
can.pack()
rect = can.create_rectangle(0, 240, 20, 260, fil='#5F6A6A')
def act():
global rect, can
pos = can.coords(rect)
if pos[2] < 1000:
can.move(rect, 5, 0)
can.update()
can.after(1)
act()
def key_down(key):
t = datetime.datetime.now()
act()
print(datetime.datetime.now() - t)
can.bind("<Button-1>", key_down)
root.mainloop()
and get these results:
i3-7100u ubuntu 20.04 laptop python3.8.5 - 0.5 seconds
i3-7100u windows 10 laptop python3.9.4 - 3 seconds
i3-6006u ubuntu 20.10 laptop python3.9.x - 0.5 seconds
i3-6006u windows 10 laptop python3.8.x - 3 seconds
i5-7200u windows 10 laptop python3.6.x - 3 seconds
i5-8400 windows 10 desktop python3.9.x - 3 seconds
fx-9830p windows 10 laptop python3.8.x - 0.5 seconds
tkinter vesrion is the same - 8.6
How can be it fixed or at least explained?
tkinter.Canvas.after should be used like so:
def act():
global rect, can
pos = can.coords(rect)
if pos[2] < 1000:
can.move(rect, 5, 0)
can.update()
can.after(1, act)
The after method is not like time.sleep. Rather than recursively calling the function, the above code schedules it to be called later, so this will break your timing code.
If you want to time it again, try this:
def act():
global rect, can, t
pos = can.coords(rect)
if pos[2] < 1000:
can.move(rect, 5, 0)
can.update()
can.after(1, act)
else:
print(datetime.datetime.now() - t)
def key_down(key):
global t
t = datetime.datetime.now()
act()
This may still take different amounts of time on different machines. This difference can be caused by a variety of things like CPU speed, the implementation of tkinter for your OS etc. The difference can be reduced by increasing the delay between iterations: tkinter.Canvas.after takes a time in milliseconds, so a delay of 16 can still give over 60 frames per seconds.
If keeping the animation speed constant is important, I would recommend you use delta time in your motion calculations rather than assuming a constant frame rate.
AS you can see from your data it doesent matter which python version. It appears that ubuntu systems can help process python easier. However, im pretty sure its just the processer or how much ram the computer has.

Change locale for Google Colab

I want to change the local setting (to change the date format) in GoogleCollab
The following works for me in JupyterNotebook but not in GoogleColab:
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
It always returns the error: unsupported locale setting
I have already looked at many other solutions and tried everything.
One solution to change only the time zone I have seen is this one:
'!rm /etc/localtime
!ln -s /usr/share/zoneinfo/Asia/Bangkok /etc/localtime
!date
I figured this one out after a long time:
In Colab, you will have to install the desired locales. You do this with:
!sudo dpkg-reconfigure locales
This will prompt for a numeric input, e.g. 268 and 269 for Hungarian.
So you enter 268 269.
It will also prompt for the default locale, after installation. Here you will need to select your desired custom locale. This time, it is a numeric selection out of 3-5 options, depending, on how many have you selected at the previous step. In my case, I have selected 3, and the default locale became hu_HU.
You need to restart the Colab runtime: Ctrl + M then .
You need to activate the locale:
import locale
locale.setlocale(locale.LC_ALL, 'hu_HU') <- make sure you do it for the LC_ALL context.
The custom locale is now ready to use with pandas:
pd.to_datetime('2021-01-01').day_name() returns Friday, but
pd.to_datetime('2021-01-01').day_name('hu_HU') returns PĂ©ntek
I wasn't successful using German locale on Google Colab, but desired formatting could be obtained as a combination of overriding locale for decimal separator and date formatting.
German formatting rules can be found here.
For custom string formatting nice cheatsheet is here.
from datetime import datetime, timedelta
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import locale
german_format_str_full = '%Y-%m-%d, %H.%M Uhr'
german_format_str_date = '%Y-%m-%d'
# genereting plot data, xs are dates with not obvious step
xs = np.arange(datetime(year=2021, month=11, day=28, hour=23, minute=59, second=59),
datetime(year=2021, month=12, day=6, hour=23, minute=59, second=59),
timedelta(hours=5,minutes=47,seconds=27))
ys = np.sin(np.arange(0,len(xs),1)) # whatever
# use overwritten locale for comma as decimal point -- German formatting
plt.rcParams['axes.formatter.use_locale'] = True
locale._override_localeconv["decimal_point"]= ','
# plot
fig, ax = plt.subplots(figsize=(9,4))
ax.plot(xs,ys, 'o-')
# set formatting string using mdates from matplotlib
ax.xaxis.set_major_formatter(mdates.DateFormatter(german_format_str_date))
# rotate formatted ticks or use autoformat 'fig.autofmt_xdate()'
plt.xticks(rotation=70)
plt.title('Google Colab plot with German locale style')
plt.show()
It gives me this plot:
If you need to check how formatting settings look like on your machine you can use locale.nl_langinfo(locale.D_T_FMT). For example:
import locale
from datetime import datetime
now = datetime.now()
# find local date time formatting on Google Colab
local_format_str = locale.nl_langinfo(locale.D_T_FMT)
print('local_format_str on Google Colab: ', local_format_str)
print('now in Google Colab default format:', now.strftime(local_format_str))
german_format_str_full = '%Y-%m-%d, %H.%M Uhr'
german_format_str_date = '%Y-%m-%d'
print('now in German format, full:',now.strftime(german_format_str_full))
print('now in German format, only date:',now.strftime(german_format_str_date))
ridiculous_format = '%Y->%m-->%d'
print('now ridiculous_format:',now.strftime(ridiculous_format))
Based on this answer I was able to load german locales. However it needs to be done in two steps: Installing new, german locale. Restarting kernel and loading german locale.
In short:
import os
# Install de_DE
!/usr/share/locales/install-language-pack de_DE
!dpkg-reconfigure locales
# Restart Python process to pick up the new locales
os.kill(os.getpid(), 9)
More detailed version:
It turned out that the list of available locales is pretty short which can be checked like this:
import locale
from datetime import datetime
now = datetime.now()
# find local date time formatting on Google Colab
local_format_str = locale.nl_langinfo(locale.D_T_FMT)
print('local_format_str on Google Colab: ', local_format_str)
print('now in Google Colab default format:', now.strftime(local_format_str))
print('Loading avaliable locales via real names...')
for real_name in set(locale.locale_alias.values()):
try:
locale.setlocale(locale.LC_ALL, real_name)
print('success: real_name = ', real_name)
except:
pass
print('Loading avaliable locales via aliases...')
for alias , real_name in locale.locale_alias.items():
try:
locale.setlocale(locale.LC_ALL, alias)
print('success: alias = ' , alias, ' , real_name = ', real_name)
except:
pass
With output:
local_format_str on Google Colab: %a %b %e %H:%M:%S %Y
now in Google Colab default format: Wed Dec 1 12:10:52 2021
Loading avaliable locales via real names...
success: real_name = en_US.UTF-8
success: real_name = C
Loading avaliable locales via aliases...
As we can see there is no german locale, so it needs to be installed with code:
import os
# Install de_DE
!/usr/share/locales/install-language-pack de_DE
!dpkg-reconfigure locales
# Restart Python process to pick up the new locales
os.kill(os.getpid(), 9)
giving an output:
Generating locales (this might take a while)...
de_DE.ISO-8859-1... done
Generation complete.
dpkg-trigger: error: must be called from a maintainer script (or with a --by-package option)
Type dpkg-trigger --help for help about this utility.
Generating locales (this might take a while)...
de_DE.ISO-8859-1... done
en_US.UTF-8... done
Generation complete.
Then we load german locale locale.setlocale(locale.LC_ALL, 'german') and the same code as at the beginning (remember about importing again packages) gives us:
Loading avaliable locales via real names...
success: real_name = C
success: real_name = en_US.UTF-8
success: real_name = de_DE.ISO8859-1
Loading avaliable locales via aliases...
success: alias = deutsch , real_name = de_DE.ISO8859-1
success: alias = german , real_name = de_DE.ISO8859-1
and the default formatting is more German:
local_format_str on Google Colab: %a %d %b %Y %T %Z
now in Google Colab default format: Mi 01 Dez 2021 12:12:03

A Question with using scapy.sniff for get the 'Ethernet Frame' in pcap files

Aim: Get the arrival time from the pcap files
Language: python3.7
Tools: Scapy.sniff
Above all ,i want get the arrival time data,in the .pcap ,when i use wireshark ,i saw the data in the Ethernet Frame,but when i use
#Scapy.sniff(offline='.pcap') ,i just get the Ether,TCP,IP and others ,so how can i get that data?
Thanx alot!
>>from scapy.all import *
>>a = sniff(offline = '***.pcap')
>>a[0]
[out]:
<Ether dst=*:*:*:*:*:* src=*:*:*:*:*:* type=** |<IP version=4 ihl=5 tos=0x20 len=52 id=14144 flags=DF frag=0 ttl=109 proto=tcp chksum=0x5e3b src=*.*.*.* dst=*.*.*.* |<TCP sport=gcsp dport=http seq=1619409885 ack=1905830025 dataofs=8 reserved=0 flags=A window=65535 chksum=0xfdb5 urgptr=0 options=[('NOP', None), ('NOP', None), ('SAck', (1905831477, 1905831485))] |>>>
[ ]:
The packet time from the pcap is available in the time member:
print(a[0].time)
It's kept as a floating point value (the standard python "timestamp" format). To get it in a form more easily understandable, you may want to use the datetime module:
>>> from datetime import datetime
>>> dt = datetime.fromtimestamp(a[0].time)
>>> print(dt)
2018-11-12 03:03:00.259780
The scapy documentation isn't great. It can be very instructive to use the interactive help facility. For example, in the interpreter:
$ python
>>> from scapy.all import *
>>> a = sniff(offline='mypcap.pcap')
>>> help(a[0])
This will show you all the methods and attributes of the object represented by a[0]. In your case, that is an instance of class Ether(scapy.packet.Packet).

Resources