the windows API does not work with python3 but works with python 2 - python-3.x

I have a python script that I'm trying to convert from python 2.7 to python 3.7.
The script includes windows API to read the system registry. In python 2.7 it works correctly. In python 3.7 it does not return the correct result.
I try to run the script python 3 in another PC with python 3. I run the script only in powershell like administrator.
https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexa this is the documentation of RegOpenKeyExA() function.
In python 2.7 I installed "VCForPython27.msi" from: https://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi which for windows 3.7 I don't find a updated version.
from ctypes import c_uint, c_char_p, byref, windll
subkey = 'JD'
def RegOpenKeyEx(subkey):
hkey = c_uint(0) ## Initialize to an int
windll.advapi32.RegOpenKeyExA(0x80000002, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\' + subkey, 0, 0xF003F , byref(hkey))
print(hkey.value)
return hkey.value
In python 2.7 the output is:
656
and the windll.advapi32.RegOpenKeyExA function returns 0 as a return value.
In python 3.7 the output is:
0
and the windll.advapi32.RegOpenKeyExA function returns 2 as a return value

I solved with replace the 6th row with:
windll.advapi32.RegOpenKeyExA(0x80000002, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\'.encode('ascii') + subkey.encode('ascii'), 0, 0x19 , byref(hkey))
In Python 2.7, strings are byte-strings by default. In Python 3.x, they are unicode by default. I explicitly making string a byte string using .encode('ascii').

Related

python psycopg2 changed dateformat

When i select in psql this
select ts_changed, to_char(ts_changed, 'YYYY-MM-DD HH24:MI:SS.MS')
from ...
i got this format.
2022-01-05 14:51:11.334
in a python script with psycopg i got this
2022-01-05 14:49:05.777000
psycopg has added three more digits i dont want, because i provides trouble with elasticsearch.
Here runs my query
pg_init_connect = 'host={} dbname={} user={}'.format(db_host, db_db, db_user)
pg_connect = psycopg2.connect(pg_init_connect)
do_sql = pg_connect.cursor()
do_sql.execute(db_query)
result = do_sql.fetchall()
pg_connect.commit()
return(result)
How to say psycopg to return the right date?

How to write Chinese characters to file based on unicode code point in Python3

I am trying to write Chinese characters to a CSV file based on their Unicode code points found in a text file in unicode.org/Public/zipped/13.0.0/Unihan.zip. For instance, one example character is U+9109.
In the example below I can get the correct output by hard coding the value (line 8), but keep getting it wrong with every permutation I've tried at generating the bytes from the code point (lines 14-16).
I'm running this in Python 3.8.3 on a Debian-based Linux distro.
Minimal working (broken) example:
1 #!/usr/bin/env python3
2
3 def main():
4
5 output = open("test.csv", "wb")
6
7 # Hardcoded values work just fine
8 output.write('\u9109'.encode("utf-8"))
9
10 # Comma separation
11 output.write(','.encode("utf-8"))
12
13 # Problem is here
14 codepoint = '9109'
15 u_str = '\\' + 'u' + codepoint
16 output.write(u_str.encode("utf-8"))
17
18 # End with newline
19 output.write('\n'.encode("utf-8"))
20
21 output.close()
22
23 if __name__ == "__main__":
24 main()
Executing and viewing results:
example $
example $./test.py
example $
example $cat test.csv
鄉,\u9109
example $
The expected output would look like this (Chinese character occurring on both sides of the comma):
example $
example $./test.py
example $cat test.csv
鄉,鄉
example $
chr is used to convert integers to code points in Python 3. Your code could use:
output.write(chr(0x9109).encode("utf-8"))
But if you specify the encoding in the open instead of using binary mode you don't have to manually encode everything. print to a file handles newlines for you as well.
with open("test.txt",'w',encoding='utf-8') as output:
for i in range(0x4e00,0x4e10):
print(f'U+{i:04X} {chr(i)}',file=output)
Output:
U+4E00 一
U+4E01 丁
U+4E02 丂
U+4E03 七
U+4E04 丄
U+4E05 丅
U+4E06 丆
U+4E07 万
U+4E08 丈
U+4E09 三
U+4E0A 上
U+4E0B 下
U+4E0C 丌
U+4E0D 不
U+4E0E 与
U+4E0F 丏

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

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.)

What became of ggsave (ggplot 0.6.8) in later versions of ggplot python

In version 0.6.8 I use ggsave() from ggplot in Python.
In version 0.11 such a function does not exist. Which one should I use to replace it?
This is the code that used to work in previous version:
import ggplot as gg
plot_data = gg.ggplot(dat, gg.aes('month', 'average_workers')) + gg.geom_line() + gg.scale_y_continuous(breaks=11) + \
gg.scale_x_discrete(breaks=list_of_years_division, labels=list_of_years) + \
gg.ggtitle('Evolution of average numbers of workers per firm, monthly\nAgents : %s' %
title_pop_val+'% of Population') + gg.xlab('Years') + gg.ylab('Units') + gg.theme_bw()
gg.ggsave(plot_data, os.path.join(parameters.output_data_path, ('temp_general_average_workers%s.png' %
parameters.parameters_names)))
plot_data is a ggplot object.
I have tried:
gg.ggplot.save(plot_data, 'path.jpg', 10, 6, 300)
And the error I get is:
TypeError: object of type 'int' has no len()
I ran into the same issue. It looks like the solution is to call 'save()' on the ggplot object:
plot_data.save(filename='path.png')

actions=[[type=ACTION_OUTPUT action=[port=1 maxLen=0]];], as keywords to get_or_create in Bulbs

I am using TitanGraphDB + Cassandra.I am starting Titan as follows
cd titan-cassandra-0.3.1
bin/titan.sh config/titan-server-rexster.xml config/titan-server-cassandra.properties
I have a Rexster shell that I can use to communicate to Titan+Cassandra above.
cd rexster-console-2.3.0
bin/rexster-console.sh
I want to program the Titan Graph DB from my python program.I am using bulbs package for that.
I create a vertex from python using bulbs as given below.
fe1 = self.g.vertices.get_or_create('switch_dpid',switch_dpid,
{'actionOutputPort':actionOutputPort,
'switch_state':'FE_SWITCH_UPDATED',
'matchInPort': MatchInPort,
'type': 'flow_entry',
'user_state':'FE_USER_ADD',
'actions': ['type':'ACTION_OUTPUT', 'action':[port=actionOutputPort maxLen=0];]})
This is giving me an error
'actions': ['type':'ACTION_OUTPUT', 'action':[port=actionOutputPort maxLen=0];]})
SyntaxError: invalid syntax
The output that I would expect from the Rexster console is as follows.
switch_dpid=00:00:00:00:00:00:02:05,
actionOutputPort=1,
switch_state=FE_SWITCH_UPDATED,
matchInPort=2,
flow_entry_id=0x4ee30a9400000012,
type=flow_entry,
actions=[[type=ACTION_OUTPUT action=[port=1 maxLen=0]];],
user_state=FE_USER_ADD
How do I program actions so that it is as above.?
You're mixing up Groovy syntax with Python.
actions is a dictionary and action is a dictionary so in Python it should be:
'actions': {'type': 'ACTION_OUTPUT',
'action': {port: actionOutputPort,
maxLen: 0}}
Note it is usually more convenient (less quotes) to create Python dictionaries using the dict function:
'actions' = dict(type = 'ACTION_OUTPUT',
action = dict(port = actionOutputPort,
maxLen = 0))

Resources