I need to print ZPL with dynamic content.
I Need your help. I am dynamic content , please help me.
is this word possible to print. Note the content is dynamic.
ZPL Code please.
If you want to type bold you can use this
^FO340,128^FDbold^FS
^FO339,128^FDbold^FS
Another option (External fonts usage for underline, italic and bold)
http://labelary.com/docs.html
There is no simple way to bold or italicize text withing ZPL. The fonts the printer has are very basic and can't be changed like that.
Complex font settings (italic, bold, serif ) are actually sent as compressed images to ZPL printers (you can check this with ZebraDesigner).
The format is called Z64, which is based on LZ77.
These two pages contain interesting code in Java to write a converter :
http://www.jcgonzalez.com/img-to-zpl-online
https://gist.github.com/trevarj/1255e5cbc08fb3f79c3f255e25989a18
...still I'm not sure whether the CRC part of the conversion will remain the same in the future, as this is probably vendor-dependent.
Here is a Python port of the first script :
import cv2
import base64
import matplotlib.pyplot as plt
import io
import numpy
blacklimit=int(50* 768/100)
compress=False
total=0
width_byte=0
mapCode = dict()
LOCAL_PATH="C://DEV//printer//zebra_debug.txt"
'''
class StringBuilder(object):
def __init__(self):
self._stringio = io.StringIO()
def __str__(self):
return self._stringio.getvalue()
def getvalue(self):
return self._stringio.getvalue()
def append(self, *objects, sep=' ', end=''):
print(*objects, sep=sep, end=end, file=self._stringio)
'''
def init_map_code():
global mapCode
mapCode[1] = "G"
mapCode[2] = "H"
mapCode[3] = "I"
mapCode[4] = "J"
mapCode[5] = "K"
mapCode[6] = "L"
mapCode[7] = "M"
mapCode[8] = "N"
mapCode[9] = "O"
mapCode[10] = "P"
mapCode[11] = "Q"
mapCode[12] = "R"
mapCode[13] = "S"
mapCode[14] = "T"
mapCode[15] = "U"
mapCode[16] = "V"
mapCode[17] = "W"
mapCode[18] = "X"
mapCode[19] = "Y"
mapCode[20] = "g"
mapCode[40] = "h"
mapCode[60] = "i"
mapCode[80] = "j"
mapCode[100] = "k"
mapCode[120] = "l"
mapCode[140] = "m"
mapCode[160] = "n"
mapCode[180] = "o"
mapCode[200] = "p"
mapCode[220] = "q"
mapCode[240] = "r"
mapCode[260] = "s"
mapCode[280] = "t"
mapCode[300] = "u"
mapCode[320] = "v"
mapCode[340] = "w"
mapCode[360] = "x"
mapCode[380] = "y"
mapCode[400] = "z"
def numberToBase(n, b):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1]
def four_byte_binary(binary_str):
decimal=int(binary_str, 2)
if decimal>15:
returned=hex(decimal).upper()
returned=returned[2:]
else:
#returned=hex(decimal).upper()+"0"
returned=hex(decimal).upper()
if binary_str!="00000000":
print("cut="+returned)
returned=returned[2:]
returned="0"+returned
if binary_str!="00000000":
print("low10="+returned)
#
if binary_str!="00000000":
print(binary_str+"\t"+str(decimal)+"\t"+returned+"\t")
return returned
def createBody(img):
global blacklimit
global width_byte
global total
height, width, colmap = img.shape
print(height)
print(width)
print(colmap)
rgb = 0
index=0
aux_binary_char=['0', '0', '0', '0', '0', '0', '0', '0']
sb=[]
if(width%8>0):
width_byte=int((width/8)+1)
else:
width_byte=width/8
total=width_byte*height
print(height)
print("\n")
print(width)
print("\n")
i=0
for h in range(0, height):
for w in range(0, width):
color = img[h,w]
#print(color)
#print(w)
blue=color[0]
green=color[1]
red=color[2]
blue=blue & 0xFF
green=green & 0xFF
red=red & 0xFF
"""
blue=np.uint8(blue)
green=np.unit8(green)
red=np.unit8(red)
"""
#print(bin(blue))
auxchar='1'
total_color=red+green+blue
if(total_color> blacklimit):
#print('above_black_limit')
auxchar='0'
aux_binary_char[index]=auxchar
index=index+1
if(index==8 or w==(width-1)):
if "".join(aux_binary_char) !="00000000":
print(i)
sb.append(four_byte_binary("".join(aux_binary_char)))
i=i+1
aux_binary_char=['0', '0', '0', '0', '0', '0', '0', '0']
index=0
#print(h)
sb.append("\n")
#print(sb)
print(blacklimit)
return ''.join(sb)
def encode_hex_ascii(code):
global width_byte
global mapCode
max_linea=width_byte*2
sb_code=[]
sb_linea=[]
previous_line=1
counter=1
aux = code[0]
first_char=False
for i in range(1, len(code)):
if(first_char):
aux=code[i]
first_char=False
continue
if(code[i]=="\n"):
if(counter>= max_linea and aux=='0'):
sb_linea.append(",")
elif(counter>= max_linea and aux=='F'):
sb_linea.append("!")
elif(counter>20):
multi20=int((counter/20))*20
resto20=counter%20
sb_linea.append(mapCode[multi20])
if(resto20!=0):
sb_linea.append(mapCode[resto20] +aux)
else:
sb_linea.append(aux)
else:
sb_linea.append(mapCode[counter] +aux)
counter=1
first_char=True
if(''.join(sb_linea)==previous_line):
sb_code.append(":")
else:
sb_code.append(''.join(sb_linea))
previous_line=''.join(sb_linea)
sb_linea=[]
continue
if aux==code[i]:
counter=counter+1
else:
if counter>20:
multi20=int((counter/20))*20
resto20=counter%20
sb_linea.append(mapCode[multi20])
if resto20!=0:
sb_linea.append(mapCode[resto20] + aux)
else:
sb_linea.append(aux)
else:
sb_linea.append(mapCode[counter] + aux)
counter=1
aux=code[i]
return ''.join(sb_code)
def head_doc():
global total
global width_byte
return "^XA " + "^FO0,0^GFA,"+ str(int(total)) + ","+ str(int(total)) + "," + str(int(width_byte)) +", "
def foot_doc():
return "^FS"+ "^XZ"
def process(img):
global compress
init_map_code()
cuerpo=createBody(img)
print("CUERPO\n")
print(cuerpo)
print("\n")
if compress:
cuerpo=encode_hex_ascii(cuerpo)
print("COMPRESS\n")
print(cuerpo)
print("\n")
return head_doc() + cuerpo + foot_doc()
img = cv2.imread("C:\\Users\\ftheeten\\Pictures\\out.jpg", cv2.IMREAD_COLOR )
compress=True
blacklimit ==int(50* 768/100)
test=process(img)
file=open(LOCAL_PATH, 'w')
file.write(test)
file.close()
Related
I have a temp sensor taht i need to use for a school project it works perfectly when i dont put it together with the rest of the code but when I do it gives a CRC error after giving me the temp 3 or 4 times.
import onewire
import time, ds18x20
from machine import Pin
ow = onewire.OneWire(Pin(26))
ds = ds18x20.DS18X20(ow)
roms = ds.scan()
print("roms=",roms) # roms= [bytearray(b'(\x19\x1e\xbf\x0b\x00\x00\xc7'), bytearray(b'(\xd2*y\x97\x13\x03\xc3')]
# https://web.alfredstate.edu/faculty/weimandn/miscellaneous/ascii/ascii_index.html
last_reading_time = 0
while(1):
ds.convert_temp()
for rom in roms:
temp=ds.read_temp(rom)
current_time = time.time() # get the current time
if current_time - last_reading_time >= 10:
last_reading_time = current_time
print(temp)
this works without a problem.
from wifi import ssid, password, mqtt_server, client_id
from machine import Pin, I2C
from time import sleep, ticks_ms
from sh1106 import SH1106_I2C
import utime
import machine
import network
from umqttsimple import MQTTClient
from var import *
import time
import urequests
import json
from Pins import *
import onewire
import time, ds18x20
buzzer.freq(500)
buzzer.duty(0)
ow = onewire.OneWire(Pin(26))
ds = ds18x20.DS18X20(ow)
roms = ds.scan()
print("roms=",roms)
topic_sub = b'CVOFOCUS/RP3/*******'
topic_pub = b'CVOFOCUS/RP3/*******'
topic_pub2 = b'CVOFOCUS/RP3/******'
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
WIDTH = 128
HEIGHT = 64
i2c = I2C(scl=Pin(22), sda=Pin(27)) #Init i2c
oled= SH1106_I2C(128, 64, i2c)
# CONSTANTS
KEY_UP = const(0)
KEY_DOWN = const(1)
gewenste_code = "7ADC"
ingegeven_code = ""
keys = [['1', '2', '3', 'A'], ['4', '5', '6', 'B'], ['7', '8', '9', 'C'], ['*', '0', '#', 'D']]
# Pin names for Pico
cols = [19,16,15,23]
rows = [2,4,5,18]
# set pins for rows as outputs
row_pins = [Pin(pin_name, mode=Pin.OUT) for pin_name in rows]
# set pins for cols as inputs
col_pins = [Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN) for pin_name in cols]
def init():
for row in range(0,4):
for col in range(0,4):
row_pins[row].value(0)
def scan(row, col):
""" scan the keypad """
# set the current column to high
row_pins[row].value(1)
key = None
# check for keypressed events
if col_pins[col].value() == KEY_DOWN:
key = KEY_DOWN
if col_pins[col].value() == KEY_UP:
key = KEY_UP
row_pins[row].value(0)
# return the key state
return key
print("starting")
# set all the columns to low
init()
def oled_text(text):
oled.fill(0)
oled.text(text, 10, 10)
oled.show()
def trigger_alarm(trig_by = ""):
global is_alarm_on, is_alarm_trigered, alarm_timer
if is_alarm_on and not is_alarm_trigered:
print("Alarm trigered by", trig_by)
is_alarm_trigered = 1
alarm_timer = ticks_ms()
def subscribe_callback(topic, msg): #b'cvofocus/wimverlinden/msg_for_esp'
print((topic, msg))
global is_alarm_on
if topic == b'CVOFOCUS/RP3/Matteo_Alarm':
if msg== b'Alarm aan':
if is_alarm_on == 0:
is_alarm_on = not is_alarm_on
print("alarm_on =" , str(is_alarm_on))
msg = b'Alarm aan'
client.publish(topic_pub, msg)
oled.text('van afstand', 10, 30)
oled.text('bediend', 10, 38)
oled.show()
elif msg ==b'Alarm off':
print("correct")
if is_alarm_on == 1:
is_alarm_on = not is_alarm_on
print("alarm_on =" , str(is_alarm_on))
if is_alarm_on == 0:
# alles uitschakelen
is_alarm_trigered = 0
led_red.value(0)
buzzer.duty(0)
oled.text('van afstand', 10, 30)
oled.text('bediend', 10, 38)
oled.show()
msg = b'Alarm uit'
client.publish(topic_pub, msg)
led_green.value(1)
sleep(0.2)
led_green.value(0)
sleep(0.2)
led_green.value(1)
sleep(0.2)
led_green.value(0)
ingegeven_code = ""
def connect_and_subscribe():
global client_id, mqtt_server, topic_sub
client = MQTTClient(client_id, mqtt_server)
client.set_callback(subscribe_callback)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
###############################
###############################
while True:
ds.convert_temp()
for rom in roms:
temp= ds.read_temp(rom)
current_time = time.time() # get the current time
if current_time - last_reading_time >= 60:
last_reading_time = current_time
msg = b"%d" % temp
client.publish(topic_pub2, msg)
print(f"temp send ({temp})")
try:
client.check_msg() # needed in loop?
status_button2 = button2.value()
if status_button_before2 != status_button2:
status_button_before2 = status_button2
if status_button2 == 0:
msg = b'PANIC PANIC PANIC PANIC!'
client.publish(topic_pub, msg)
response = urequests.post(api_endpoint, data=json.dumps({
"token": app_token,
"user": user_key,
"message": message,
"sound": sound,
"priority": priority,
"retry": retry,
"expire": expire,
}), headers={"Content-type": "application/json"})
print(response.text)
except OSError as e:
restart_and_reconnect()
status_button = button.value()
if status_button_before != status_button:
status_button_before = status_button
if status_button == 0:
if is_alarm_on == 0:
is_alarm_on = not is_alarm_on
print("alarm_on =" , str(is_alarm_on))
msg = b'Alarm aan'
client.publish(topic_pub, msg)
sleep(0.05)
if is_alarm_on:
if ticks_ms() - timestamp_led > 200:
timestamp_led = ticks_ms()
is_led_on = not is_led_on
#print("is_led_on", is_led_on)
pir_status = pir.value()
if pir_status != status_pir_before:
status_pir_before = pir_status
print("PIR=" , pir_status)
if pir_status == 1:
trigger_alarm("PIR")
if is_alarm_trigered:
if ticks_ms() - timestamp_buzzer > 500:
timestamp_buzzer = ticks_ms()
is_buzzer_on = not is_buzzer_on
#print("is_buzzer_on", is_buzzer_on)
buzzer.duty(512 * is_buzzer_on)
if is_alarm_on == True:
led_red.value(1)
oled.fill(0)
for row in range(4):
for col in range(4):
key = scan(row, col)
if key == KEY_DOWN:
oled.text("Key Pressed: ",10,0)
print("Key Pressed", keys[row][col])
oled.text(keys[row][col], 55, 30)
oled.show()
##MATTEO
ingegeven_code += keys[row][col]
print(ingegeven_code)
if len(ingegeven_code) > 3:
oled.fill(0)
oled.show()
if ingegeven_code == gewenste_code:
oled.text("correct",35,0)
print("correct")
if is_alarm_on == 1:
is_alarm_on = not is_alarm_on
print("alarm_on =" , str(is_alarm_on))
if is_alarm_on == 0:
# alles uitschakelen
is_alarm_trigered = 0
led_red.value(0)
buzzer.duty(0)
oled.text(ingegeven_code, 45, 30)
oled.show()
led_green.value(1)
sleep(0.2)
led_green.value(0)
sleep(0.2)
led_green.value(1)
sleep(0.2)
led_green.value(0)
msg = b'Alarm uit'
client.publish(topic_pub, msg)
oled.fill(0)
oled.show()
ingegeven_code = ""
else:
oled.text("incorrect", 29,0)
print("incorrect")
oled.text(ingegeven_code, 45, 30)
oled.show()
oled.show()
ingegeven_code = ""
sleep(0.3)
last_key_press = keys[row][col]
And here it doesn't.
(I know some of the code might be mesy but the stuf about the temp sensor is on line 20-24 and 165-175)
Traceback (most recent call last):
File "main.py", line 169, in <module>
File "ds18x20.py", line 40, in read_temp
File "ds18x20.py", line 30, in read_scratch
Exception: CRC error
and this is the error i get.
i have tried connecting it to a different ESP32 and it gives the same.
I'm mostly confused beacouse it does work apart but not toggeter with the rest of my code.
(Skip to hash-tags if in a hurry)
This program will only work if it ends on the image showing.
I want to use it as a function inside another looping program, but it will not work. It will display the stats of the Pokemon(p.whatever), but the image will not show. The image will show in IDLE Python 3.4, but not the terminal. I've been stuck on this for months.
Here is the program that works(in IDLE Python 3.4, not the terminal):
import pykemon
print('What are you looking for?')
askedpokemon = input()
pokemonInDatabase = False
while pokemonInDatabase == False:
pokemonInDatabase = True
try:
if ('1' in askedpokemon) or ('2' in askedpokemon) or ('3' in askedpokemon) or ('4' in askedpokemon) or ('5' in askedpokemon) or ('6' in askedpokemon) or ('7' in askedpokemon) or ('8' in askedpokemon) or ('9' in askedpokemon):
p = (pykemon.get(pokemon_id = askedpokemon))
else:
askedpokemon = askedpokemon.lower()
p = (pykemon.get(pokemon = askedpokemon))
#Turns askedpokemon into number
askedpokemon = p.resource_uri
askedpokemon = askedpokemon.replace('/api/v1/pokemon/',' ')
askedpokemon = askedpokemon.replace('/',' ')
askedpokemon = askedpokemon.strip()
except pykemon.exceptions.ResourceNotFoundError:
print(askedpokemon + " is not a valid Pokemon name or id number.")
print('Try another')
askedpokemon = input()
pokemonInDatabase = False
print (p)
pTypes = (p.types)
for key, value in pTypes.items() :
pTypes = str(key)
print (' Type: ' + pTypes)
print (' HP: ' + str(p.hp))
print (' Attack: ' + str(p.attack))
print ('Defense: ' + str(p.defense))
print (' Sp Atk: ' + str(p.sp_atk))
print (' Sp Def: ' + str(p.sp_def))
print (' Speed: ' + str(p.speed))
print ('Exp Yield: ' + str(p.exp))
#######################################################
import time
import urllib
import urllib.request
import tkinter as tk
root = tk.Tk()
url = "http://assets22.pokemon.com/assets/cms2/img/pokedex/full/526.png"
if len(askedpokemon) < 3:
if len(askedpokemon) == 2:
askedpokemon = ('0' + askedpokemon)
if len(askedpokemon) == 1:
askedpokemon = ('00' + askedpokemon)
url = url.replace('526', askedpokemon)
u = urllib.request.urlopen(url)
raw_data = u.read()
u.close()
import base64
b64_data = base64.encodestring(raw_data)
image = tk.PhotoImage(data=b64_data)
label = tk.Label(image=image)
label.pack()
##########################################################
Below is the working program with its modules.
https://drive.google.com/file/d/0B3Q4wQpL0nDUYWFFSjV3cUhXVWc/view?usp=sharing
Here is an mcve that illustrates the problem. Call the file tem.py.
import tkinter as tk
root = tk.Tk()
image = tk.PhotoImage(file='python.png')
label = tk.Label(image=image)
label.pack()
When you run in a terminal, this runs, but the root window closes after label.pack(), before you can see it. Either put root.mainloop() at the end of the code or run with python -i tem.py (as IDLE, in effect, does). The -i says to switch from batch to interactive mode after the end of the program instead of closing. IDLE does this so one can interact with the live program before it is closed.
nltk have nice word2word similarity function which measures similarity by how close the terms are to the common hypernym. Although that similarity function is not applicable to the situation where 2 terms differ from pos tag to pos tag, it still is great.
However, I found that it is so slow... It was 10x times slower than just term matching. Is there anyway the nltk similarity function become faster?
I have tested with this code below:
from nltk import stem, RegexpStemmer
from nltk.corpus import wordnet, stopwords
from nltk.tag import pos_tag
import time
file1 = open('./tester.csv', 'r')
def similarityCal(word1, word2):
synset1 = wordnet.synsets(word1)
synset2 = wordnet.synsets(word2)
if len(synset1) != 0 and len(synset2) != 0:
wordFromList1 = synset1[0]
wordFromList2 = synset2[0]
return wordFromList1.wup_similarity(wordFromList2)
else:
return 0
start_time = time.time()
file1lines = file1.readlines()
stopwords = stopwords.words('english')
previousLine = ""
currentLine = ""
cntOri = 0
cntExp = 0
for line1 in file1lines:
currentLine = line1.lower().strip()
if previousLine == "":
previousLine = currentLine
continue
else:
for tag1 in pos_tag(currentLine.split(" ")):
tmpStr1 = tag1[0];
if tmpStr1 not in stopwords and len(tmpStr1) > 1:
if tmpStr1 in previousLine:
print("termMatching word", tmpStr1);
cntOri = cntOri + 1
for tag2 in pos_tag(previousLine.split(" ")):
tmpStr2 = tag2[0];
if tag1[1].startswith("NN") and tag2[1].startswith("NN") or tag1[1].startswith("VB") and tag2[1].startswith("VB"):
value = similarityCal(tmpStr1, tmpStr2)
if type(value) is float and value > 0.8:
print(tmpStr1, " similar to " , tmpStr2 , " ", value)
cntExp = cntExp + 1
previousLine = currentLine
end_time = time.time()
print ("time taken : ",end_time - start_time, " // ", cntOri, " | ", cntExp)
file1.close()
I just comment out similarity function to compare the performance.
And I have used samples from this site:
https://www.briandunning.com/sample-data/
Any ideas?
I need to access all memory of a running process in my local Windows 7-64bit. I am new to winapi.
Here is my problem; Whenever I try to Open a process and reads its memory, I get Access is Denied error.
I searched and found something. It is said that If I run the main process as Administrator and use PROCESS_ALL_ACCESS on OpenProcess, I would have enough right to do it as it is said. OK, I did it. but nothing is changed. On reading memory, I still get Access is Denied.
So, I kept searching and found another thing which is enabling SeDebugPrivilege. I have also done that but nothing is changed. I still get the error.
I've read the quest and his answer here;
Windows Vista/Win7 Privilege Problem: SeDebugPrivilege & OpenProcess .
But as I said, I am really new to winapi. I could not solve my problem yet. Is there anything which which I need to configure in my local operating system?
Here is my Python code with pywin32;
from _ctypes import byref, sizeof, Structure
from ctypes import windll, WinError, c_buffer, c_void_p, create_string_buffer
from ctypes.wintypes import *
import win32security
import win32api
import gc
import ntsecuritycon
from struct import Struct
from win32con import PROCESS_ALL_ACCESS
from struct import calcsize
MEMORY_STATES = {0x1000: "MEM_COMMIT", 0x10000: "MEM_FREE", 0x2000: "MEM_RESERVE"}
MEMORY_PROTECTIONS = {0x10: "PAGE_EXECUTE", 0x20: "PAGE_EXECUTE_READ", 0x40: "PAGEEXECUTE_READWRITE",
0x80: "PAGE_EXECUTE_WRITECOPY", 0x01: "PAGE_NOACCESS", 0x04: "PAGE_READWRITE",
0x08: "PAGE_WRITECOPY"}
MEMORY_TYPES = {0x1000000: "MEM_IMAGE", 0x40000: "MEM_MAPPED", 0x20000: "MEM_PRIVATE"}
class MEMORY_BASIC_INFORMATION(Structure):
_fields_ = [
("BaseAddress", c_void_p),
("AllocationBase", c_void_p),
("AllocationProtect", DWORD),
("RegionSize", UINT),
("State", DWORD),
("Protect", DWORD),
("Type", DWORD)
]
class SYSTEM_INFO(Structure):
_fields_ = [("wProcessorArchitecture", WORD),
("wReserved", WORD),
("dwPageSize", DWORD),
("lpMinimumApplicationAddress", DWORD),
("lpMaximumApplicationAddress", DWORD),
("dwActiveProcessorMask", DWORD),
("dwNumberOfProcessors", DWORD),
("dwProcessorType", DWORD),
("dwAllocationGranularity", DWORD),
("wProcessorLevel", WORD),
("wProcessorRevision", WORD)]
class PyMEMORY_BASIC_INFORMATION:
def __init__(self, MBI):
self.MBI = MBI
self.set_attributes()
def set_attributes(self):
self.BaseAddress = self.MBI.BaseAddress
self.AllocationBase = self.MBI.AllocationBase
self.AllocationProtect = MEMORY_PROTECTIONS.get(self.MBI.AllocationProtect, self.MBI.AllocationProtect)
self.RegionSize = self.MBI.RegionSize
self.State = MEMORY_STATES.get(self.MBI.State, self.MBI.State)
# self.Protect = self.MBI.Protect # uncomment this and comment next line if you want to do a bitwise check on Protect.
self.Protect = MEMORY_PROTECTIONS.get(self.MBI.Protect, self.MBI.Protect)
self.Type = MEMORY_TYPES.get(self.MBI.Type, self.MBI.Type)
ASSUME_ALIGNMENT = True
class TARGET:
"""Given a ctype (initialized or not) this coordinates all the information needed to read, write and compare."""
def __init__(self, ctype):
self.alignment = 1
self.ctype = ctype
# size of target data
self.size = sizeof(ctype)
self.type = ctype._type_
# get the format type needed for struct.unpack/pack.
while hasattr(self.type, "_type_"):
self.type = self.type._type_
# string_buffers and char arrays have _type_ 'c'
# but that makes it slightly slower to unpack
# so swap is for 's'.
if self.type == "c":
self.type = "s"
# calculate byte alignment. this speeds up scanning substantially
# because we can read and compare every alignment bytes
# instead of every single byte.
# although if we are scanning for a string the alignment is defaulted to 1 \
# (im not sure if this is correct).
elif ASSUME_ALIGNMENT:
# calc alignment
divider = 1
for i in xrange(4):
divider *= 2
if not self.size % divider:
self.alignment = divider
# size of target ctype.
self.type_size = calcsize(self.type)
# length of target / array length.
self.length = self.size / self.type_size
self.value = getattr(ctype, "raw", ctype.value)
# the format string used for struct.pack/unpack.
self.format = str(self.length) + self.type
# efficient packer / unpacker for our own format.
self.packer = Struct(self.format)
def get_packed(self):
"""Gets the byte representation of the ctype value for use with WriteProcessMemory."""
return self.packer.pack(self.value)
def __str__(self):
return str(self.ctype)[:10] + "..." + " <" + str(self.value)[:10] + "..." + ">"
class Memory(object):
def __init__(self, process_handle, target):
self._process_handle = process_handle
self._target = target
self.found = []
self.__scann_process()
def __scann_process(self):
"""scans a processes pages for the target value."""
si = SYSTEM_INFO()
psi = byref(si)
windll.kernel32.GetSystemInfo(psi)
base_address = si.lpMinimumApplicationAddress
max_address = si.lpMaximumApplicationAddress
page_address = base_address
while page_address < max_address:
page_address = self.__scan_page(page_address)
if len(self.found) >= 60000000:
print("[Warning] Scan ended early because too many addresses were found to hold the target data.")
break
gc.collect()
return self.found
def __scan_page(self, page_address):
"""Scans the entire page for TARGET instance and returns the next page address and found addresses."""
information = self.VirtualQueryEx(page_address)
base_address = information.BaseAddress
region_size = information.RegionSize
next_region = base_address + region_size
size = self._target.size
target_value = self._target.value
step = self._target.alignment
unpacker = self._target.packer.unpack
if information.Type != "MEM_PRIVATE" or \
region_size < size or \
information.State != "MEM_COMMIT" or \
information.Protect not in ["PAGE_EXECUTE_READ", "PAGEEXECUTE_READWRITE", "PAGE_READWRITE"]:
return next_region
page_bytes = self.ReadMemory(base_address, region_size)
for i in xrange(0, (region_size - size), step):
partial = page_bytes[i:i + size]
if unpacker(partial)[0] == target_value:
self.found.append(base_address + i)
del page_bytes # free the buffer
return next_region
def ReadMemory(self, address, size):
cbuffer = c_buffer(size)
success = windll.kernel32.ReadProcessMemory(
self._process_handle,
address,
cbuffer,
size,
0)
assert success, "ReadMemory Failed with success == %s and address == %s and size == %s.\n%s" % (
success, address, size, WinError(win32api.GetLastError()))
return cbuffer.raw
def VirtualQueryEx(self, address):
MBI = MEMORY_BASIC_INFORMATION()
MBI_pointer = byref(MBI)
size = sizeof(MBI)
success = windll.kernel32.VirtualQueryEx(
self._process_handle,
address,
MBI_pointer,
size)
assert success, "VirtualQueryEx Failed with success == %s.\n%s" % (
success, WinError(win32api.GetLastError())[1])
assert success == size, "VirtualQueryEx Failed because not all data was written."
return PyMEMORY_BASIC_INFORMATION(MBI)
def AdjustPrivilege(priv):
flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
p = win32api.GetCurrentProcess()
htoken = win32security.OpenProcessToken(p, flags)
id = win32security.LookupPrivilegeValue(None, priv)
newPrivileges = [(id, win32security.SE_PRIVILEGE_ENABLED)]
win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
win32api.CloseHandle(htoken)
def OpenProcess(pid=win32api.GetCurrentProcessId()):
# ntsecuritycon.SE_DEBUG_NAME = "SeDebugPrivilege"
AdjustPrivilege(ntsecuritycon.SE_DEBUG_NAME)
phandle = windll.kernel32.OpenProcess( \
PROCESS_ALL_ACCESS,
0,
pid)
assert phandle, "Failed to open process!\n%s" % WinError(win32api.GetLastError())[1]
return phandle
PID = 22852
process_handle = OpenProcess(PID)
Memory(process_handle, TARGET(create_string_buffer("1456")))
Here is the error I always get;
AssertionError: ReadMemory Failed with success == 0 and address == 131072 and size == 4096.
[Error 5] Access is denied.
I do not know what information else about my code and my personal Windows 7 operating system, I should provide to you. If you need to know more, please ask it from me, I will provide it to solve that problem.
I guess, this is about a lack of configuration in my operating system , not about pywin32. I'll be waiting for your solutions.
I made this game in python 2.7 and it worked in .py format but when I compiled it with py2exe it suddenly broke. It gave me this error:
"Microsoft Visuak C++ Runtime Library
Runtime Error!
Program C:\Python27\Helmetdodger\Stuffz\main.exe
This application has requested the Runtime to terminate it in an unusual way.
Please contact the program's support team."
The code:
import pygame
import random, sys, os
from pygame.locals import *
WINDOWWIDTH = 1200
WINDOWHEIGHT = 900
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
def terminate():
pygame.quit()
os.exit(1)
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Helmetdodger')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
# set up images
playerImage1 = pygame.image.load('player1.png')
powerImage = pygame.image.load('power.png')
playerRect = playerImage1.get_rect()
baddieImage1 = pygame.image.load('baddie.png')
baddieImage2 = pygame.image.load('baddie1.png')
baddieImage3 = pygame.image.load('baddie2.png')
baddieImage4 = pygame.image.load('baddie3.png')
baddieImage5 = pygame.image.load('baddie4.png')
baddieImage6 = pygame.image.load('baddie5.png')
baddieImage7 = pygame.image.load('baddie6.png')
baddieImage8 = pygame.image.load('baddie7.png')
baddieImage9 = pygame.image.load('baddie8.png')
baddieImage10 = pygame.image.load('baddie9.png')
baddieImage11 = pygame.image.load('baddie10.png')
baddieImage12 = pygame.image.load('baddie11.png')
baddieImage13 = pygame.image.load('baddie12.png')
baddieImage14 = pygame.image.load('baddie13.png')
baddieImage15 = pygame.image.load('baddie14.png')
baddieImage16 = pygame.image.load('baddie15.png')
baddieImage17 = pygame.image.load('baddie16.png')
baddieImage18 = pygame.image.load('baddie17.png')
baddieImage19 = pygame.image.load('baddie18.png')
baddieImage20 = pygame.image.load('baddie19.png')
baddieImage21 = pygame.image.load('baddie20.png')
baddieImage22 = pygame.image.load('baddie21.png')
baddieImage23 = pygame.image.load('baddie22.png')
baddieImage24 = pygame.image.load('baddie23.png')
baddieImage25 = pygame.image.load('baddie24.png')
baddieImage26 = pygame.image.load('baddie25.png')
baddieImage27 = pygame.image.load('baddie26.png')
baddieImage28 = pygame.image.load('baddie27.png')
baddieImage29 = pygame.image.load('baddie28.png')
baddieImage30 = pygame.image.load('baddie29.png')
baddieImages = [baddieImage1, baddieImage2, baddieImage3, baddieImage4, baddieImage5, baddieImage6, baddieImage7, baddieImage8, baddieImage9, baddieImage10, baddieImage11, baddieImage12, baddieImage13, baddieImage14, baddieImage15, baddieImage16, baddieImage17, baddieImage18, baddieImage19, baddieImage20, baddieImage21, baddieImage22, baddieImage23, baddieImage24, baddieImage25, baddieImage26, baddieImage27, baddieImage28, baddieImage29, baddieImage20]
# show the "Start" screen
drawText('Helmetdodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
#Get highscore
topScore = 0
try:
file = open('hs.txt', "r")
topScore = file.read()
topScore = int(topScore)
file.close()
except:
topScore = 0
while True:
# set up the start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
powerCount = 0
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieCount = random.randrange(len(baddieImages))
baddieAddCounter = 0
baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(baddieImages[baddieCount], (baddieSize, baddieSize)),
}
baddies.append(newBaddie)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
# Move the baddies down.
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
# Delete baddies that have fallen past the bottom.
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage1, playerRect)
# Draw each baddie
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
topScore = score # set new top score
file = open("hs.txt", "w")
score = str(score)
file.write(score)
file.close()
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
My buildscript was incorrect, I found a better buildscript online to use instead
try:
from distutils.core import setup
import py2exe, pygame
from modulefinder import Module
import glob, fnmatch
import sys, os, shutil
import operator
except ImportError, message:
raise SystemExit, "Unable to load module. %s" % message
#hack which fixes the pygame mixer and pygame font
origIsSystemDLL = py2exe.build_exe.isSystemDLL # save the orginal before we edit it
def isSystemDLL(pathname):
# checks if the freetype and ogg dll files are being included
if os.path.basename(pathname).lower() in ("libfreetype-6.dll", "libogg-0.dll","sdl_ttf.dll"): # "sdl_ttf.dll" added by arit.
return 0
return origIsSystemDLL(pathname) # return the orginal function
py2exe.build_exe.isSystemDLL = isSystemDLL # override the default function with this one
class pygame2exe(py2exe.build_exe.py2exe): #This hack make sure that pygame default font is copied: no need to modify code for specifying default font
def copy_extensions(self, extensions):
#Get pygame default font
pygamedir = os.path.split(pygame.base.__file__)[0]
pygame_default_font = os.path.join(pygamedir, pygame.font.get_default_font())
#Add font to list of extension to be copied
extensions.append(Module("pygame.font", pygame_default_font))
py2exe.build_exe.py2exe.copy_extensions(self, extensions)
class BuildExe:
def __init__(self):
#Name of starting + .py
self.script = "raw.py"
#Name of program
self.project_name = "main"
#Project url
self.project_url = "about:none"
#Version of program
self.project_version = "0.0"
#License of the program
self.license = "MyApps License"
#Auhor of program
self.author_name = "Me"
self.author_email = "example#example.com"
self.copyright = "Copyright (c) 2009 Me."
#Description
self.project_description = "MyApps Description"
#Icon file (None will use pygame default icon)
self.icon_file = None
#Extra files/dirs copied to game
self.extra_datas = []
#Extra/excludes python modules
self.extra_modules = []
self.exclude_modules = []
#DLL Excludes
self.exclude_dll = ['']
#python scripts (strings) to be included, seperated by a comma
self.extra_scripts = []
#Zip file name (None will bundle files in exe instead of zip file)
self.zipfile_name = None
#Dist directory
self.dist_dir ='C:\Python27\dist'
## Code from DistUtils tutorial at http://wiki.python.org/moin/Distutils/Tutorial
## Originally borrowed from wxPython's setup and config files
def opj(self, *args):
path = os.path.join(*args)
return os.path.normpath(path)
def find_data_files(self, srcdir, *wildcards, **kw):
# get a list of all files under the srcdir matching wildcards,
# returned in a format to be used for install_data
def walk_helper(arg, dirname, files):
if '.svn' in dirname:
return
names = []
lst, wildcards = arg
for wc in wildcards:
wc_name = self.opj(dirname, wc)
for f in files:
filename = self.opj(dirname, f)
if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):
names.append(filename)
if names:
lst.append( (dirname, names ) )
file_list = []
recursive = kw.get('recursive', True)
if recursive:
os.path.walk(srcdir, walk_helper, (file_list, wildcards))
else:
walk_helper((file_list, wildcards),
srcdir,
[os.path.basename(f) for f in glob.glob(self.opj(srcdir, '*'))])
return file_list
def run(self):
if os.path.isdir(self.dist_dir): #Erase previous destination dir
shutil.rmtree(self.dist_dir)
#Use the default pygame icon, if none given
if self.icon_file == None:
path = os.path.split(pygame.__file__)[0]
self.icon_file = os.path.join(path, 'pygame.ico')
#List all data files to add
extra_datas = []
for data in self.extra_datas:
if os.path.isdir(data):
extra_datas.extend(self.find_data_files(data, '*'))
else:
extra_datas.append(('.', [data]))
setup(
cmdclass = {'py2exe': pygame2exe},
version = self.project_version,
description = self.project_description,
name = self.project_name,
url = self.project_url,
author = self.author_name,
author_email = self.author_email,
license = self.license,
# targets to build
windows = [{
'script': self.script,
'icon_resources': [(0, self.icon_file)],
'copyright': self.copyright
}],
options = {'py2exe': {'optimize': 2, 'bundle_files': 2, 'compressed': True, \
'excludes': self.exclude_modules, 'packages': self.extra_modules, \
'dll_excludes': self.exclude_dll,
'includes': self.extra_scripts} },
zipfile = self.zipfile_name,
data_files = extra_datas,
dist_dir = self.dist_dir
)
if os.path.isdir('build'): #Clean up build dir
shutil.rmtree('build')
if __name__ == '__main__':
if operator.lt(len(sys.argv), 2):
sys.argv.append('py2exe')
BuildExe().run() #Run generation
raw_input("Press any key to continue") #Pause to let user see that things ends