Replace string before brace in Python-script - python-2.7
I modified jtaubers python script to convert betababel-code to the original greek letters. After some modifications (and help!) I got the script to run.
# beta2unicode.py
#
# Version 2004-11-23
#
# James Tauber
# http://jtauber.com/
#
# You are free to redistribute this, but please inform me of any errors
#
# USAGE:
#
# trie = beta2unicodeTrie()
# beta = "LO/GOS\n";
# unicode, remainder = trie.convert(beta)
#
# - to get final sigma, string must end in \n
# - remainder will contain rest of beta if not all can be converted
class Trie:
def __init__(self):
self.root = [None, {}]
def add(self, key, value):
curr_node = self.root
for ch in key:
curr_node = curr_node[1].setdefault(ch, [None, {}])
curr_node[0] = value
def find(self, key):
curr_node = self.root
for ch in key:
try:
curr_node = curr_node[1][ch]
except KeyError:
return None
return curr_node[0]
def findp(self, key):
curr_node = self.root
remainder = key
for ch in key:
try:
curr_node = curr_node[1][ch]
except KeyError:
return (curr_node[0], remainder)
remainder = remainder[1:]
return (curr_node[0], remainder)
def convert(self, keystring):
valuestring = ""
key = keystring
while key:
value, key = self.findp(key)
if not value:
return (valuestring, key)
valuestring += value
return (valuestring, key)
def beta2unicodeTrie():
t = Trie()
t.add("*A", u"\u0391")
t.add("*B", u"\u0392")
t.add("*G", u"\u0393")
t.add("*D", u"\u0394")
t.add("*E", u"\u0395")
t.add("*Z", u"\u0396")
t.add("*H", u"\u0397")
t.add("*Q", u"\u0398")
t.add("*I", u"\u0399")
t.add("*K", u"\u039A")
t.add("*L", u"\u039B")
t.add("*M", u"\u039C")
t.add("*N", u"\u039D")
t.add("*C", u"\u039E")
t.add("*O", u"\u039F")
t.add("*P", u"\u03A0")
t.add("*R", u"\u03A1")
t.add("*S", u"\u03A3")
t.add("*T", u"\u03A4")
t.add("*U", u"\u03A5")
t.add("*F", u"\u03A6")
t.add("*X", u"\u03A7")
t.add("*Y", u"\u03A8")
t.add("*W", u"\u03A9")
t.add("A", u"\u03B1")
t.add("B", u"\u03B2")
t.add("G", u"\u03B3")
t.add("D", u"\u03B4")
t.add("E", u"\u03B5")
t.add("Z", u"\u03B6")
t.add("H", u"\u03B7")
t.add("Q", u"\u03B8")
t.add("I", u"\u03B9")
t.add("K", u"\u03BA")
t.add("L", u"\u03BB")
t.add("M", u"\u03BC")
t.add("N", u"\u03BD")
t.add("C", u"\u03BE")
t.add("O", u"\u03BF")
t.add("P", u"\u03C0")
t.add("R", u"\u03C1")
t.add("S\n", u"\u03C2")
t.add("S,", u"\u03C2,")
t.add("S.", u"\u03C2.")
t.add("S:", u"\u03C2:")
t.add("S}", u"\u03C2:")
t.add("S;", u"\u03C2;")
t.add("S]", u"\u03C2]")
t.add("S#", u"\u03C2#")
t.add("S_", u"\u03C2_")
t.add("S", u"\u03C3")
t.add("T", u"\u03C4")
t.add("U", u"\u03C5")
t.add("F", u"\u03C6")
t.add("X", u"\u03C7")
t.add("Y", u"\u03C8")
t.add("W", u"\u03C9")
t.add("I+", U"\u03CA")
t.add("U+", U"\u03CB")
t.add("A)", u"\u1F00")
t.add("A(", u"\u1F01")
t.add("A)\\", u"\u1F02")
t.add("A(\\", u"\u1F03")
t.add("A)!", u"\u1F02")
t.add("A(!", u"\u1F03")
t.add("A)/", u"\u1F04")
t.add("A(/", u"\u1F05")
t.add("E)", u"\u1F10")
t.add("E(", u"\u1F11")
t.add("E)\\", u"\u1F12")
t.add("E(\\", u"\u1F13")
t.add("E)!", u"\u1F12")
t.add("E(!", u"\u1F13")
t.add("E)/", u"\u1F14")
t.add("E(/", u"\u1F15")
t.add("H)", u"\u1F20")
t.add("H(", u"\u1F21")
t.add("H)\\", u"\u1F22")
t.add("H(\\", u"\u1F23")
t.add("H)!", u"\u1F22")
t.add("H(!", u"\u1F23")
t.add("H)/", u"\u1F24")
t.add("H(/", u"\u1F25")
t.add("I)", u"\u1F30")
t.add("I(", u"\u1F31")
t.add("I)\\", u"\u1F32")
t.add("I(\\", u"\u1F33")
t.add("I)!", u"\u1F32")
t.add("I(!", u"\u1F33")
t.add("I)/", u"\u1F34")
t.add("I(/", u"\u1F35")
t.add("O)", u"\u1F40")
t.add("O(", u"\u1F41")
t.add("O)\\", u"\u1F42")
t.add("O(\\", u"\u1F43")
t.add("O)!", u"\u1F42")
t.add("O(!", u"\u1F43")
t.add("O)/", u"\u1F44")
t.add("O(/", u"\u1F45")
t.add("U)", u"\u1F50")
t.add("U(", u"\u1F51")
t.add("U)\\", u"\u1F52")
t.add("U(\\", u"\u1F53")
t.add("U)!", u"\u1F52")
t.add("U(!", u"\u1F53")
t.add("U)/", u"\u1F54")
t.add("U(/", u"\u1F55")
t.add("W)", u"\u1F60")
t.add("W(", u"\u1F61")
t.add("W)\\", u"\u1F62")
t.add("W(\\", u"\u1F63")
t.add("W)!", u"\u1F62")
t.add("W(!", u"\u1F63")
t.add("W)/", u"\u1F64")
t.add("W(/", u"\u1F65")
t.add("A)=", u"\u1F06")
t.add("A(=", u"\u1F07")
t.add("H)=", u"\u1F26")
t.add("H(=", u"\u1F27")
t.add("I)=", u"\u1F36")
t.add("I(=", u"\u1F37")
t.add("U)=", u"\u1F56")
t.add("U(=", u"\u1F57")
t.add("W)=", u"\u1F66")
t.add("W(=", u"\u1F67")
t.add("*A)", u"\u1F08")
t.add("*)A", u"\u1F08")
t.add("*A(", u"\u1F09")
t.add("*(A", u"\u1F09")
#
t.add("*(\A", u"\u1F0B")
t.add("*A)/", u"\u1F0C")
t.add("*)/A", u"\u1F0C")
t.add("*A(/", u"\u1F0F")
t.add("*(/A", u"\u1F0F")
t.add("*E)", u"\u1F18")
t.add("*)E", u"\u1F18")
t.add("*E(", u"\u1F19")
t.add("*(E", u"\u1F19")
#
t.add("*(\E", u"\u1F1B")
t.add("*E)/", u"\u1F1C")
t.add("*)/E", u"\u1F1C")
t.add("*E(/", u"\u1F1D")
t.add("*(/E", u"\u1F1D")
t.add("*H)", u"\u1F28")
t.add("*)H", u"\u1F28")
t.add("*H(", u"\u1F29")
t.add("*(H", u"\u1F29")
t.add("*H)\\", u"\u1F2A")
t.add(")\\*H", u"\u1F2A")
t.add("*)\\H", u"\u1F2A")
t.add("*H)!", u"\u1F2A")
t.add(")!*H", u"\u1F2A")
t.add("*)!H", u"\u1F2A")
#
t.add("*H)/", u"\u1F2C")
t.add("*)/H", u"\u1F2C")
#
t.add("*)=H", u"\u1F2E")
t.add("(/*H", u"\u1F2F")
t.add("*(/H", u"\u1F2F")
t.add("*I)", u"\u1F38")
t.add("*)I", u"\u1F38")
t.add("*I(", u"\u1F39")
t.add("*(I", u"\u1F39")
#
#
t.add("*I)/", u"\u1F3C")
t.add("*)/I", u"\u1F3C")
#
#
t.add("*I(/", u"\u1F3F")
t.add("*(/I", u"\u1F3F")
#
t.add("*O)", u"\u1F48")
t.add("*)O", u"\u1F48")
t.add("*O(", u"\u1F49")
t.add("*(O", u"\u1F49")
#
#
t.add("*(\O", u"\u1F4B")
t.add("*O)/", u"\u1F4C")
t.add("*)/O", u"\u1F4C")
t.add("*O(/", u"\u1F4F")
t.add("*(/O", u"\u1F4F")
#
t.add("*U(", u"\u1F59")
t.add("*(U", u"\u1F59")
#
t.add("*(/U", u"\u1F5D")
#
t.add("*(=U", u"\u1F5F")
t.add("*W)", u"\u1F68")
t.add("*W(", u"\u1F69")
t.add("*(W", u"\u1F69")
#
#
t.add("*W)/", u"\u1F6C")
t.add("*)/W", u"\u1F6C")
t.add("*W(/", u"\u1F6F")
t.add("*(/W", u"\u1F6F")
t.add("*A)=", u"\u1F0E")
t.add("*)=A", u"\u1F0E")
t.add("*A(=", u"\u1F0F")
t.add("*W)=", u"\u1F6E")
t.add("*)=W", u"\u1F6E")
t.add("*W(=", u"\u1F6F")
t.add("*(=W", u"\u1F6F")
t.add("A\\", u"\u1F70")
t.add("A!", u"\u1F70")
t.add("A/", u"\u1F71")
t.add("E\\", u"\u1F72")
t.add("E!", u"\u1F72")
t.add("E/", u"\u1F73")
t.add("H\\", u"\u1F74")
t.add("H!", u"\u1F74")
t.add("H/", u"\u1F75")
t.add("I\\", u"\u1F76")
t.add("I!", u"\u1F76")
t.add("I/", u"\u1F77")
t.add("O\\", u"\u1F78")
t.add("O!", u"\u1F78")
t.add("O/", u"\u1F79")
t.add("U\\", u"\u1F7A")
t.add("U!", u"\u1F7A")
t.add("U/", u"\u1F7B")
t.add("W\\", u"\u1F7C")
t.add("W!", u"\u1F7C")
t.add("W/", u"\u1F7D")
t.add("A)/|", u"\u1F84")
t.add("A(/|", u"\u1F85")
t.add("H)|", u"\u1F90")
t.add("H(|", u"\u1F91")
t.add("H)/|", u"\u1F94")
t.add("H)=|", u"\u1F96")
t.add("H(=|", u"\u1F97")
t.add("W)|", u"\u1FA0")
t.add("W(=|", u"\u1FA7")
t.add("A=", u"\u1FB6")
t.add("H=", u"\u1FC6")
t.add("I=", u"\u1FD6")
t.add("U=", u"\u1FE6")
t.add("W=", u"\u1FF6")
t.add("I\\+", u"\u1FD2")
t.add("I!+", u"\u1FD2")
t.add("I/+", u"\u1FD3")
t.add("I+/", u"\u1FD3")
t.add("U\\+", u"\u1FE2")
t.add("U!+", u"\u1FE2")
t.add("U/+", u"\u1FE3")
t.add("A|", u"\u1FB3")
t.add("A/|", u"\u1FB4")
t.add("H|", u"\u1FC3")
t.add("H/|", u"\u1FC4")
t.add("W|", u"\u1FF3")
t.add("W|/", u"\u1FF4")
t.add("W/|", u"\u1FF4")
t.add("A=|", u"\u1FB7")
t.add("H=|", u"\u1FC7")
t.add("W=|", u"\u1FF7")
t.add("R(", u"\u1FE4")
t.add("*R(", u"\u1FEC")
t.add("*(R", u"\u1FEC")
# t.add("~", u"~")
# t.add("-", u"-")
# t.add("(null)", u"(null)")
# t.add("&", "&")
t.add("0", u"0")
t.add("1", u"1")
t.add("2", u"2")
t.add("3", u"3")
t.add("4", u"4")
t.add("5", u"5")
t.add("6", u"6")
t.add("7", u"7")
t.add("8", u"8")
t.add("9", u"9")
t.add("#", u"#")
t.add("$", u"$")
t.add(" ", u" ")
t.add(".", u".")
t.add(",", u",")
t.add("'", u"'")
t.add(":", u":")
t.add(";", u";")
t.add("_", u"_")
t.add("[", u"[")
t.add("]", u"]")
t.add("\n", u"")
return t
import sys
t = beta2unicodeTrie()
import re
BCODE = re.compile(r'\\bcode{[^}]*}')
for line in open(sys.argv[1]):
matches = BCODE.search(line)
for match in BCODE.findall(line):
bcode = match[7:-1]
a, b = t.convert(bcode.upper())
if b:
raise IOError("failed conversion '%s' in '%s'" % (b, line))
converted = a.encode("utf-8")
line = line.replace(match, converted)
print(line.rstrip())
There is one thing left though. The final sigma "ς" gets not converted like this when it stands at the end of the \bcode{}-Makro. For example here:
\bcode{ei)=dos}
The script converts it to the normal sigma "σ" Unicode: U+03C3
How do I make the script recognize to convert the "s" when it stands right before the end-brace to the Unicode U+03C2?
This:
t.add("S}", u"\u03C2}")
does not do the trick
Related
\u0000 cannot be converted to text in django/postgreSQl
i have a project with django .on the host when i want to upload an image sometime error occurred(problem with specific images)! the below show how i resize uploaded images: def save_files_to_media(request, is_public=False, klass=None, conversation=None): from apps.file.models import File fs = FileSystemStorage() file_items = {} for data_item in request.data: file_match = re.search('^fileToUpload\[(\d+)\]$', data_item) if file_match and file_match.groups(): item_index = file_match.groups()[0] if item_index not in file_items: file_items[item_index] = {} file_items[item_index]['file_to_upload'] = request.data[data_item] else: optimize_match = re.search('^optimizeType\[(\d+)\]$', data_item) if optimize_match and optimize_match.groups(): item_index = optimize_match.groups()[0] if item_index not in file_items: file_items[item_index] = {} file_items[item_index]['optimize_type'] = request.data[data_item] files = [] for file_item_key in file_items: input_file = file_items[file_item_key]['file_to_upload'] # TODO: checking validation. if input_file.name is not exist optimize_type = file_items[file_item_key].get('optimize_type') file_uuid = str(uuid4()) if is_public: orig_filename, file_ext = splitext(basename(input_file.name)) directory_name = join(settings.MEDIA_ROOT, file_uuid) filename = file_uuid + file_ext else: directory_name = join(settings.MEDIA_ROOT, file_uuid) mkdir(directory_name) filename = input_file.name filepath = join(directory_name, filename) fs.save(filepath, input_file) is_optimized = False if optimize_type == 'image': is_success, filepath = image_optimizer(filepath) filename = basename(filepath) is_optimized = is_success file_obj = File( orig_name=filename, uuid=file_uuid, md5sum=get_md5sum(filepath), filesize=get_filesize(filepath), meta=get_meta_info(filepath), is_optimized=is_optimized, creator=request.user ) if is_public: file_obj.is_public = True else: file_obj.klass = klass file_obj.conversation = conversation file_obj.save() files.append(file_obj) return files here is the error i got with some images: unsupported Unicode escape sequence LINE 1: ..., 'ada90ead20f7994837dced344266cc51', 145216, '', '{"FileTyp... ^ DETAIL: \u0000 cannot be converted to text. CONTEXT: JSON data, line 1: ...ecTimeDigitized": 506779, "MakerNoteUnknownText": its funny that in my local but not in host. for more information i must tell you guys my postgreSQL version is 11.3 and host postgreSQl is 9.5.17 . where you think is problem? as error it's seems for postgreSQL. thank you
Preserve empty message in ruamel.yaml roundtrip parsing
Using ruamel.yaml, the output of roundtrip parsing of the YAML a: {b: } is a: {b: !!null ''} Is there any way to preserve the empty message, or overwrite the None representer to output an empty message as above?
This is not trivial and I am not sure if the solution presented below doesn't have adverse side-effects. The cause for the non-triviality has to do with multiple things: You are using the less readable flow style a: {b: } instead of block style: a: b: The latter round-trips without a change The empty value for key b loads as None, which I have not been able to subclass in ruamel.yaml, and hence style information cannot be attached to that value, and you have to rely on the "default" emitter (which in your case doesn't do what you want). This a: {b:} is entirely different from your a: {b: } and currently the emitter goes for safe and inserts tag information into the stream. With that background information, you can force the style of the representation for None to the empty string and based on that hack the emitter: import sys import ruamel.yaml yaml_str = """\ a: {b: } """ class MyEmitter(ruamel.yaml.emitter.Emitter): def choose_scalar_style(self): # override selection for 'null' if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) if self.event.style == '"' or self.canonical: return '"' if (not self.event.style or self.event.style == '?') and \ (self.event.implicit[0] or not self.event.implicit[2]): if (not (self.simple_key_context and (self.analysis.empty or self.analysis.multiline)) and (self.flow_level and self.analysis.allow_flow_plain or (not self.flow_level and self.analysis.allow_block_plain))): return '' if (self.event.style == '') and self.event.tag == 'tag:yaml.org,2002:null' and \ (self.event.implicit[0] or not self.event.implicit[2]): if self.flow_level and not self.analysis.allow_flow_plain: return '' self.analysis.allow_block = True if self.event.style and self.event.style in '|>': if (not self.flow_level and not self.simple_key_context and self.analysis.allow_block): return self.event.style if not self.event.style and self.analysis.allow_double_quoted: if "'" in self.event.value or '\n' in self.event.value: return '"' if not self.event.style or self.event.style == '\'': if (self.analysis.allow_single_quoted and not (self.simple_key_context and self.analysis.multiline)): return '\'' return '"' def process_scalar(self): # if style '' and tag is 'null' insert empty space if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) if self.style is None: self.style = self.choose_scalar_style() split = (not self.simple_key_context) if self.sequence_context and not self.flow_level: self.write_indent() if self.style == '"': self.write_double_quoted(self.analysis.scalar, split) elif self.style == '\'': self.write_single_quoted(self.analysis.scalar, split) elif self.style == '>': self.write_folded(self.analysis.scalar) elif self.style == '|': self.write_literal(self.analysis.scalar) elif self.event.tag == 'tag:yaml.org,2002:null': self.stream.write(u' ') # not sure if this doesn't break other things else: self.write_plain(self.analysis.scalar, split) self.analysis = None self.style = None if self.event.comment: self.write_post_comment(self.event) class MyRepresenter(ruamel.yaml.representer.RoundTripRepresenter): def represent_none(self, data): if len(self.represented_objects) == 0 and not self.serializer.use_explicit_start: # this will be open ended (although it is not yet) return self.represent_scalar(u'tag:yaml.org,2002:null', u'null') return self.represent_scalar(u'tag:yaml.org,2002:null', u'', style='') MyRepresenter.add_representer(type(None), MyRepresenter.represent_none) yaml = ruamel.yaml.YAML() yaml.Emitter = MyEmitter yaml.Representer = MyRepresenter data = yaml.load(yaml_str) yaml.dump(data, sys.stdout) which gives: a: {b: }
Regular expression to find function definitions in Python file
I have a python project with function definitions written in CamelCase style. I'm trying to write a script to convert them to snake_case style. CaseFormatter class import re class CaseFormatter: def __init__(self, file_directory): self.first_cap_re = re.compile('(.)([A-Z][a-z]+)') self.all_cap_re = re.compile('([a-z0-9])([A-Z])') self.functions_dict = {} self.file_directory = file_directory self.file = open(file_directory, "r", encoding="UTF-8") self.file_content = self.file.read() self.names_dictionary = {} def convert_camel_case_to_snake_case(self, name): """this function convert a camel case name to a snake case name """ s1 = self.first_cap_re.sub(r'\1_\2', name) self.names_dictionary[name] = self.all_cap_re.sub(r'\1_\2', s1).lower() def find_camel_case_functions(self): """this function finds camel case functions in a file """ s1 = re.findall("^\s*def (\S+)\s*\(\s*\S+\s*(?:,\s*\S+)*\):$", self.file_content) return s1 def replace_functions(self): # file_content = open(self.file_directory, "r", encoding="UTF-8").read() self.file_content = self.file_content.replace(";", "") for key, val in self.names_dictionary.items(): self.file_content = self.file_content.replace(key, val) # print(self.file_content) self.file = open(self.file_directory, "w", encoding="UTF-8") print(self.file_content) self.file.write(self.file_content) testing the CaseFormatter class import os from CaseFormatter import * walk_dir = 'some dirctory' print('walk_dir = ' + walk_dir) print('walk_dir (absolute) = ' + os.path.abspath(walk_dir)) for root, subDirs, files in os.walk(walk_dir): print('--\nroot = ' + root) for filename in files: file_path = os.path.join(root, filename) if filename.endswith('.py') and filename != "__init__.py": print('\t- file %s (full path: %s)' % (filename, file_path)) case_formatter = CaseFormatter(file_path) # print(case_formatter.find_camel_case_functions()) for function_name in case_formatter.find_camel_case_functions(): case_formatter.convert_camel_case_to_snake_case(function_name) print(case_formatter.names_dictionary) case_formatter.replace_functions() I found the RegEx to find function definitions here. When I tried it on my project it gave me no results, the RegEx didn't work as I think. As an example of one of the files in the project: class UnvoweledPattern(object): String = '' Rules = [] IDs = [] def __init__(self, string, rules, ids): self.String = string self.Rules = rules self.IDs = ids pass def GetRootsStringsAndRules(self, string): if (string == None): string = self.String rootStrings = [] rootRules = [] for j in range(len(self.Rules)): rootRule = '' rootString = '' for k in range(len(self.Rules[j])): rootRule += self.Rules[j][k] if self.Rules[j][k].isdigit(): rootString += string[int(self.Rules[j][k]) - 1] else: rootString += self.Rules[j][k] rootStrings.append(rootString) rootRules.append(rootRule) return [rootStrings, rootRules]
Using Python Tkinter .config() method
I am trying to use the Python Tkinter .config() method to update some message text. I can't get it to work. What might I be doing wrong (see the update_message method): #!/usr/bin/python import alsaaudio as aa import audioop import Tkinter as tk import tkFont import threading import Queue # styles BACKROUND_COLOR = '#000000' TYPEFACE = 'Unit-Bold' FONT_SIZE = 50 TEXT_COLOR = '#777777' TEXTBOX_WIDTH = 400 # text TITLE = 'listen closely' SCORE_MESSAGE = 'your score:\n ' END_MESSAGE = 'too loud!\ntry again' # configuration DEVICE = 'hw:1' # hardware sound card index CHANNELS = 1 SAMPLE_RATE = 8000 # Hz // 44100 PERIOD = 256 # Frames // 256 FORMAT = aa.PCM_FORMAT_S8 # Sound format NOISE_THRESHOLD = 3 class Display(object): def __init__(self, parent, queue): self.parent = parent self.queue = queue self._geom = '200x200+0+0' parent.geometry("{0}x{1}+0+0".format( parent.winfo_screenwidth(), parent.winfo_screenheight())) parent.overrideredirect(1) parent.title(TITLE) parent.configure(background=BACKROUND_COLOR) parent.displayFont = tkFont.Font(family=TYPEFACE, size=FONT_SIZE) self.process_queue() def process_queue(self): try: score = self.queue.get(0) self.print_message(score) except Queue.Empty: pass self.parent.after(100, self.update_queue) def update_queue(self): try: score = self.queue.get(0) self.update_message(score) except Queue.Empty: pass self.parent.after(100, self.update_queue) def print_message(self, messageString): print 'message', messageString displayString = SCORE_MESSAGE + str(messageString) self.message = tk.Message( self.parent, text=displayString, bg=BACKROUND_COLOR, font=self.parent.displayFont, fg=TEXT_COLOR, width=TEXTBOX_WIDTH, justify="c") self.message.place(relx=.5, rely=.5, anchor="c") def update_message(self, messageString): print 'message', messageString displayString = SCORE_MESSAGE + str(messageString) self.message.config(text=displayString) def setup_audio(queue, stop_event): data_in = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NONBLOCK, 'hw:1') data_in.setchannels(2) data_in.setrate(44100) data_in.setformat(aa.PCM_FORMAT_S16_LE) data_in.setperiodsize(256) while not stop_event.is_set(): # Read data from device l, data = data_in.read() if l: # catch frame error try: max_vol = audioop.rms(data, 2) scaled_vol = max_vol // 4680 print scaled_vol if scaled_vol <= 3: # Too quiet, ignore continue queue.put(scaled_vol) except audioop.error, e: if e.message != "not a whole number of frames": raise e def main(): root = tk.Tk() queue = Queue.Queue() window = Display(root, queue) stop_event = threading.Event() audio_thread = threading.Thread(target=setup_audio, args=[queue, stop_event]) audio_thread.start() try: root.mainloop() finally: stop_event.set() audio_thread.join() pass if __name__ == '__main__': main() I don't want to be laying down a new message every time I update. If the .config() doesn't work, is there another method to update the text configuration of the message?
I would use string variables, first create your string variable then set it to want you want it to display at the start next make your object and in text put the sting variable then when you want to change the text in the object change the string variable. self.messaget = StringVar() self.messaget.set("") self.message = tk.Message( self.parent, textvariable=self.messaget, bg=BACKROUND_COLOR, font=self.parent.displayFont, fg=TEXT_COLOR, width=TEXTBOX_WIDTH, justify="c").grid() #note renember to palce the object after you have created it either using #.grid(row = , column =) or .pack() #note that it is textvariable instead of text if you put text instead it will run but #but will show PY_Var instead of the value of the variable edit to change the text without recreating the object you do the name of the string variable you have used and .set self.messaget.set("hi")
python script to read and write a path to registry
I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again. My code looks as below. def OnOk(self, event): data1=self.field1.GetValue() #path selected in setting window aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE) keyVal=OpenKey(aReg,r"SOFTWARE\my path to\Registry", 0,KEY_WRITE) try: SetValueEx(keyVal,"Log file",0,REG_SZ,data1) except EnvironmentError: pass CloseKey(keyVal) CloseKey(aReg) I get a error like below: Traceback (most recent call last): File "D:\PROJECT\project.py", line 305, in OnOk keyVal=OpenKey(aReg,r"SOFTWARE\my path to\Registry", 0,KEY_WRITE) WindowsError: [Error 5] Access is denied And to read from registry,the saved registry has to show up in the setting window.I tried with the below code.Though its working but not satisfied with the way i programmed it.Help me out for the better solution key = OpenKey(HKEY_CURRENT_USER, r'Software\my path to\Registry', 0, KEY_READ) for i in range(4): try: n,v,t = EnumValue(key,i) if i==0: self.field2.SetValue(v) elif i==1: self.field3.SetValue(v) elif i==2: self.field4.SetValue(v) elif i==3: self.field1.SetValue(v) except EnvironmentError: pass CloseKey(key)
#Python3 version of hugo24's snippet import winreg REG_PATH = r"Control Panel\Mouse" def set_reg(name, value): try: winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH) registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE) winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value) winreg.CloseKey(registry_key) return True except WindowsError: return False def get_reg(name): try: registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_READ) value, regtype = winreg.QueryValueEx(registry_key, name) winreg.CloseKey(registry_key) return value except WindowsError: return None #Example MouseSensitivity #Read value print (get_reg('MouseSensitivity')) #Set Value 1/20 (will just write the value to reg, the changed mouse val requires a win re-log to apply*) set_reg('MouseSensitivity', str(10)) #*For instant apply of SystemParameters like the mouse speed on-write, you can use win32gui/SPI #http://docs.activestate.com/activepython/3.4/pywin32/win32gui__SystemParametersInfo_meth.html
Same as #Aramanethota but with pep8 and func def for easy usage. REG_PATH = r"SOFTWARE\my_program\Settings" def set_reg(name, value): try: _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH) registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0, _winreg.KEY_WRITE) _winreg.SetValueEx(registry_key, name, 0, _winreg.REG_SZ, value) _winreg.CloseKey(registry_key) return True except WindowsError: return False def get_reg(name): try: registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0, _winreg.KEY_READ) value, regtype = _winreg.QueryValueEx(registry_key, name) _winreg.CloseKey(registry_key) return value except WindowsError: return None
Python script to read from registry is as follows: try: root_key=OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\my path to\Registry', 0, KEY_READ) [Pathname,regtype]=(QueryValueEx(root_key,"Pathname")) CloseKey(root_key) if (""==Pathname): raise WindowsError except WindowsError: return [""] Python script to write to the registry is: try: keyval=r"SOFTWARE\my path to\Registry" if not os.path.exists("keyval"): key = CreateKey(HKEY_CURRENT_USER,keyval) Registrykey= OpenKey(HKEY_CURRENT_USER, r"SOFTWARE\my path to\Registry", 0,KEY_WRITE) SetValueEx(Registrykey,"Pathname",0,REG_SZ,Pathname) CloseKey(Registrykey) return True except WindowsError: return False Hope it helps you all.Cheers:)
Reading registry keys: def read(path, root=HKEY_CURRENT_USER): path, name = os.path.split(path) with suppress(FileNotFoundError), OpenKey(root, path) as key: return QueryValueEx(key, name)[0] And writing: def write(path, value, root=HKEY_CURRENT_USER): path, name = os.path.split(path) with OpenKey(root, path, 0, KEY_WRITE) as key: SetValueEx(key, name, 0, REG_SZ, value) Extended for type handling. Provide type as argument, match current type in registry or python value type. def write(path, value, root=HKEY_CURRENT_USER, regtype=None): path, name = os.path.split(path) with OpenKey(root, path, 0, KEY_WRITE|KEY_READ) as key: with suppress(FileNotFoundError): regtype = regtype or QueryValueEx(key, name)[1] SetValueEx(key, name, 0, regtype or REG_DWORD if isinstance(value, int) else REG_SZ, str(value) if regtype==REG_SZ else value) NOTE: Use of contextlib.suppress() (available since python 3.4) can be replaced by try..except..pass for older versions. The context manager interface for winreg was introduced in python 2.6.
Looks like you don't have permission to edit the Registry. Incase if you are Admin, Please run this script in Elevated state.
Here is a class I wrote (python 2) which has the ability to restore state when you finish manipulating the registry. The class was not tested properly so it may contain some bugs: import _winreg as winreg class Registry(object): def __init__(self, restore_state=False): self.m_backup = {} self.m_restore_state = restore_state def get_key(self, hkey, subkey, access, create_if_doesnt_exist=True): created_key = False registry_key = None try: registry_key = winreg.OpenKey(hkey, subkey, 0, access) except WindowsError: try: if create_if_doesnt_exist: registry_key = winreg.CreateKey(hkey, subkey) if registry_key not in self.m_backup: self.m_backup[registry_key] = ({}, (hkey, subkey)) else: registry_key = None except WindowsError: if registry_key: self.close_key(registry_key) raise Exception('Registry does not exist and could not be created.') return registry_key def close_key(self, registry_key): closed = False if registry_key: try: winreg.CloseKey(registry_key) closed = True except: closed = False return closed def get_reg_value(self, hkey, subkey, name): value = None registry_key = self.get_key(hkey, subkey, winreg.KEY_READ, False) if registry_key: try: value, _ = winreg.QueryValueEx(registry_key, name) except WindowsError: value = None finally: self.close_key(registry_key) return value def set_reg_value(self, hkey, subkey, name, type, value): registry_key = self.get_key(hkey, subkey, winreg.KEY_WRITE, True) backed_up = False was_set = False if registry_key: if self.m_restore_state: if registry_key not in self.m_backup: self.m_backup[registry_key] = ({}, None) existing_value = self.get_reg_value(hkey, subkey, name) if existing_value: self.m_backup[registry_key][0][name] = (existing_value, type, False) else: self.m_backup[registry_key][0][name] = (None, None, True) backed_up = True try: winreg.SetValueEx(registry_key, name, 0, type, value) was_set = True except WindowsError: was_set = False finally: if not backed_up: self.close_key(registry_key) return was_set def restore_state(self): if self.m_restore_state: for registry_key, data in self.m_backup.iteritems(): backup_dict, key_info = data try: for name, backup_data in backup_dict.iteritems(): value, type, was_created = backup_data if was_created: print registry_key, name winreg.DeleteValue(registry_key, name) else: winreg.SetValueEx(registry_key, name, 0, type, value) if key_info: hkey, subkey = key_info winreg.DeleteKey(hkey, subkey) except: raise Exception('Could not restore value') self.close_key(registry_key) def __del__(self): if self.m_restore_state: self.restore_state()
for Creating / writing values in registry key: from winreg import* import winreg keyVal = r'SOFTWARE\\python' try: key = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS) except: key = CreateKey(HKEY_LOCAL_MACHINE, keyVal) SetValueEx(key, "Start Page", 0, REG_SZ, "snakes") CloseKey(key) If access denied - try running the command (CMd or IDE) in administrative mode for reading value in registry-key from winreg import* Registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE) RawKey = OpenKey(Registry, "SOFTWARE\\python") try: i = 0 while 1: name, value, type = EnumValue(RawKey, i) print("name:",name,"value:", value,"i:", i) i += 1 except WindowsError: print("")
My solution: def add_key(name,pathh): try: keyval=r"System\my path\Register" if not os.path.exists("keyval"): key = winreg.CreateKey(winreg.HKEY_CURRENT_USER,keyval) Registrykey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"System\my path\Register", 0,winreg.KEY_WRITE) winreg.SetValueEx(Registrykey,name,1,winreg.REG_SZ,pathh) winreg.CloseKey(Registrykey) return True except WindowsError: return False
The 'winreg' module is so ...strange working module, so, I wrote a class called 'WindowsRegistry' for working with Windows registry and 'winreg' module easier. I hope it will be more usefull: import winreg import re class WindowsRegistry: """Class WindowsRegistry is using for easy manipulating Windows registry. Methods ------- query_value(full_path : str) Check value for existing. get_value(full_path : str) Get value's data. set_value(full_path : str, value : str, value_type='REG_SZ' : str) Create a new value with data or set data to an existing value. delete_value(full_path : str) Delete an existing value. query_key(full_path : str) Check key for existing. delete_key(full_path : str) Delete an existing key(only without subkeys). Examples: WindowsRegistry.set_value('HKCU/Software/Microsoft/Windows/CurrentVersion/Run', 'Program', r'"c:\Dir1\program.exe"') WindowsRegistry.delete_value('HKEY_CURRENT_USER/Software/Microsoft/Windows/CurrentVersion/Run/Program') """ #staticmethod def __parse_data(full_path): full_path = re.sub(r'/', r'\\', full_path) hive = re.sub(r'\\.*$', '', full_path) if not hive: raise ValueError('Invalid \'full_path\' param.') if len(hive) <= 4: if hive == 'HKLM': hive = 'HKEY_LOCAL_MACHINE' elif hive == 'HKCU': hive = 'HKEY_CURRENT_USER' elif hive == 'HKCR': hive = 'HKEY_CLASSES_ROOT' elif hive == 'HKU': hive = 'HKEY_USERS' reg_key = re.sub(r'^[A-Z_]*\\', '', full_path) reg_key = re.sub(r'\\[^\\]+$', '', reg_key) reg_value = re.sub(r'^.*\\', '', full_path) return hive, reg_key, reg_value #staticmethod def query_value(full_path): value_list = WindowsRegistry.__parse_data(full_path) try: opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1], 0, winreg.KEY_READ) winreg.QueryValueEx(opened_key, value_list[2]) winreg.CloseKey(opened_key) return True except WindowsError: return False #staticmethod def get_value(full_path): value_list = WindowsRegistry.__parse_data(full_path) try: opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1], 0, winreg.KEY_READ) value_of_value, value_type = winreg.QueryValueEx(opened_key, value_list[2]) winreg.CloseKey(opened_key) return value_of_value except WindowsError: return None #staticmethod def set_value(full_path, value, value_type='REG_SZ'): value_list = WindowsRegistry.__parse_data(full_path) try: winreg.CreateKey(getattr(winreg, value_list[0]), value_list[1]) opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1], 0, winreg.KEY_WRITE) winreg.SetValueEx(opened_key, value_list[2], 0, getattr(winreg, value_type), value) winreg.CloseKey(opened_key) return True except WindowsError: return False #staticmethod def delete_value(full_path): value_list = WindowsRegistry.__parse_data(full_path) try: opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1], 0, winreg.KEY_WRITE) winreg.DeleteValue(opened_key, value_list[2]) winreg.CloseKey(opened_key) return True except WindowsError: return False #staticmethod def query_key(full_path): value_list = WindowsRegistry.__parse_data(full_path) try: opened_key = winreg.OpenKey(getattr(winreg, value_list[0]), value_list[1] + r'\\' + value_list[2], 0, winreg.KEY_READ) winreg.CloseKey(opened_key) return True except WindowsError: return False #staticmethod def delete_key(full_path): value_list = WindowsRegistry.__parse_data(full_path) try: winreg.DeleteKey(getattr(winreg, value_list[0]), value_list[1] + r'\\' + value_list[2]) return True except WindowsError: return False