Is there a character limit for win32print.TextOut() in python - python

I have been referring to Tim Golden python docs and I used the code under "Single image: use PIL and win32ui" on TimGoldenPrintGuide.
I'm trying to print a long bill with an image on the top. For printing the image I have used the same code as in the guide. I have used the code below instead of hDC.DrawText to add the text. If I have a very long text its not getting printed till the end. I used the win32print.WritePrinter to print the same text file and I got it completely. But now as I need to print an image on top I have to use this method with a device context.
In there I pass my string to this TextOut command. So is there is a character length how can I bypass it? Or what is the best way of doing this?
printer_name = sys.argv[1]
filename = sys.argv[2]
image_path = sys.argv[3]
pointSize = int(sys.argv[4])
bill_format = ""
with open(filename) as f:
for line in f:
bill_format += line
for line in (bill_format).split("\n"):
hDC.TextOut((printer_margins[0] + line_space),Y,line)
Y += int (line_space * 1.25)

Related

Python 3.6 new line with user input

Made a program that allows the user to enter some text and have a text file be created with that text inside it. However, when the user puts \n it doesn't start a new line. Finding it very difficult to use my program to create text files as it writes all the text on one line lol
Thanks
EDIT - Sorry. Here is my code (Just the part we are concerned with).
class ReadWriteEdit:
def Read(File):
ReadFile = open(File,"r").read()
print(ReadFile)
def Write(File, Text):
WriteFile = open(File,"w")
WriteFile.write(Text)
def Edit(File, Text):
EditFile = open(File,"a")
EditFile.write(Text)
def Write():
print("WRITE")
print("Enter a file location / name")
FileInput = input("-:")
print("Enter some text")
TextInput = input("-:")
ReadWriteEdit.Write(FileInput, TextInput)
As you have found, special escaped characters are not interpolated in strings read from input, because normally we want to preserve characters, not give them special meanings.
You need to do some adjustment after the input, for example:
>>> s=input()
hello\nworld
>>> s
'hello\\nworld'
>>> s = s.replace('\\n', '\n')
>>> s
'hello\nworld'
>>> print(s)
hello
world
You can just add your input to the variable. You didn't provide any code so I'll just have to improvise:
data = open('output.txt', 'w')
a = input('>>')
data.write(a + '\n')
data.close()
But the better solution would be, like the comment below me mentioned, to use sys.stdin.readline()
import sys
data.write(sys.stdin.readline())
The easiest (dirtiest?) way IMHO is to print the message and then use input() without a prompt (or with the last part of it)
print("Are we REALLY sure?\n")
answer = input("[Y/n]")

Format path within Text File for consumption in Python

I am writing a Python script for use by multiple non-Python users.
I have a text file containing the parameters my script needs to run.
One of the inputs is a path. I cannot get my script to run and was thinking it was because I had referenced my path incorrectly.
I have tried:
C:\temp\test
"C:\temp\test"
r"C:\temp\test"
C:/temp/test
"C:/temp/test"
C:\\temp\\test
"C:\\temp\\test"
I have added each one of these into a text file, which is called and read in my Python script.
I have other parameters and they are called correctly, my script seems to run when I hard code the path in. I say seems because I think there are a few bugs I need to check, but it runs with no errors.
When I use the text file I get this error - which varies depending on if I used one of the above examples:
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect: 'c:\temp\match1\jpg\n/.'
My code is as follows:
print ("Linking new attachments to feature")
fp = open(r"C:\temp\Match1\Match_Table.txt","r") #reads my text file with inputs
lines=fp.readlines()
InFeat = lines[1]
print (InFeat)
AttFolder = lines[3] #reads the folder from the text file
print (AttFolder)
OutTable = lines[5]
if arcpy.Exists(OutTable):
print("Table Exists")
arcpy.Delete_management(OutTable)
OutTable = lines[5]
print (OutTable)
LinkF = lines[7]
print (LinkF)
fp.close()
#adding from https://community.esri.com/thread/90280
if arcpy.Exists("in_memory\\matchtable"):
arcpy.Delete_management("in_memory\\matchtable")
print ("CK Done")
input = InFeat
inputField = "OBJECTID"
matchTable = arcpy.CreateTable_management("in_memory", "matchtable")
matchField = "MatchID"
pathField = "Filename"
print ("Table Created")
arcpy.AddField_management(matchTable, matchField, "TEXT")
arcpy.AddField_management(matchTable, pathField, "TEXT")
picFolder = r"C:\temp\match1\JPG" #hard coded in
print (picFolder)
print ("Fields added")
fields = ["MatchID", "Filename"]
cursor = arcpy.da.InsertCursor(matchTable, fields)
##go thru the picFolder of .png images to attach
for file in os.listdir(picFolder):
if str(file).find(".jpg") > -1:
pos = int(str(file).find("."))
newfile = str(file)[0:pos]
cursor.insertRow((newfile, file))
del cursor
arcpy.AddAttachments_management(input, inputField, matchTable, matchField, pathField, picFolder)
From your error "'c:\temp\match1\jpg\n/.'", i can see "\n" character, \n is symbole of new line ( when you press enter button ) you should remove that character from end of your path! did you try to do that? you can use .lstrip("\n") , replcae() or regx methods for remove that character.
Try to open and read line by line of your input file like this:
read_lines = [line.rstrip('\n') for line in open(r"C:\temp\Match1\Match_Table.txt")]
print(read_lines)
print(read_lines[1])

Working with txt file Changing values

I am working on a project where I have to edit offsets manually in CNC programs. I would like to do this in python, however, my experience with it has not involved something like this. Any help is greatly appreciated.
example of code:
N0880M41
N0890G50S3600
M03
N0900G96S0210M03
N0910Z23.274M08
N0920M07
N0930Z23.2063
N0940X1.39
N0950G99
N0960G01X1.29F.009
N0970X1.2558
N0980G02X1.189Z23.1662R.944
N0990G01Z14.7569F.012
N1000G02X1.2558Z14.7168R.944
N1010G01X1.29
N1020G00X1.3608Z14.7522
N1030Z23.1309
N1040X1.2656
N1050G01X1.189Z23.1662F.009
N1060G02X1.088Z23.0955R.944
N1070G01Z14.8276F.012
N1080G02X1.2528Z14.7185R.944
N1090G00X1.3236Z14.7538
N1100Z23.0602
N1110X1.1646
N1120G01X1.088Z23.0955F.009
N1130G02X.987Z23.0075R.944
N1140G01Z14.9157F.012
N1150G02X1.1446Z14.7864R.944
N1160G00X1.2152Z14.8217
N1170Z22.9721
N1180X1.0636
N1190G01X.987Z23.0075F.009
N1200G02X.886Z22.8873R.944
N1210G01Z15.0359F.012
N1220G02X1.0344Z14.8716R.944
N1230G00X1.105Z14.907
N1240Z22.8519
I need to change the Z value with a user input via prompt and I wanted to have it output with the same text as the input just with a new value in Z
for example: user prompted and entered value .226
input = N0910Z23.274M08
I would like output to be
output = N0910Z23.500M08
Here is a quick and dirty program that does what you want:
# GCode utility - adjust Z offset
# This code assumes Python 3
import re
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
# Regular expression to recognize a Z parameter
z_re = re.compile("Z(-?\d+(?:\.\d*)?)", re.I)
# Create callback function for re.sub
def make_z_callback(dz, fmt="Z{:0.4f}"):
def z_callback(match):
z_value = match.group(1) # get just the number
z_value = float(z_value) + dz # add offset
return fmt.format(z_value) # convert back to string
return z_callback
def main():
# read GCode file contents
fname = input("Enter GCode file name: ")
with open(fname) as inf:
gcode = inf.read()
# do search-and-replace on Z parameters
z_offset = get_float("Enter Z offset: ")
z_callback = make_z_callback(z_offset)
gcode = z_re.sub(z_callback, gcode)
# write result back to file
with open(fname, "w") as outf:
outf.write(gcode)
if __name__=="__main__":
main()

Why does my file show up blank in python?

I'm trying to get my python file to save numbers into a text file, but it always goes blank when I try it. I've done this many times before but it refuses to work this time.
openfile = 'example'
total = 0.5 #another example
totalstr = str(total)
file = open("%s.txt" % (openfile), "w")
file.write(totalstr)
file.close
"file" is a standard Python type. You want to rename things a bit. I'm also assuming "openfile" should be the string filename you want to use. Both answers so far are correct but putting them together gives:
my_file_name = "myfile"
total = 0.5
my_file_handle = open("%s.txt" %(my_file_name), "w")
my_file_handle.write(str(total))
my_file_handle.close()
file is a keyword in python. So,
print '%s' %(file)
prints
<type 'file'>
You should use:
openfile = 'file'
This works for me:
openfile = "file"
total = 0.5
totalstr = str(total)
file = open("%s.txt" % (openfile), "w")
file.write(totalstr)
file.close()
See if you can spot the changes.

Insert text into a text file following specific text using Python

I have to edit some text files to include new information, but I will need to insert that information at specific locations in the file based on the surrounding text.
This doesn't work the way I need it to:
with open(full_filename, "r+") as f:
lines = f.readlines()
for line in lines:
if 'identifying text' in line:
offset = f.tell()
f.seek(offset)
f.write('Inserted text')
...in that it adds the text to the end of the file. How would I write it to the next line following the identifying text?
(AFAICT, this is not a duplicate of similar questions, since none of those were able to provide this answer)
If you don't need to work in place, then maybe something like:
with open("old.txt") as f_old, open("new.txt", "w") as f_new:
for line in f_old:
f_new.write(line)
if 'identifier' in line:
f_new.write("extra stuff\n")
(or, to be Python-2.5 compatible):
f_old = open("old.txt")
f_new = open("new.txt", "w")
for line in f_old:
f_new.write(line)
if 'identifier' in line:
f_new.write("extra stuff\n")
f_old.close()
f_new.close()
which turns
>>> !cat old.txt
a
b
c
d identifier
e
into
>>> !cat new.txt
a
b
c
d identifier
extra stuff
e
(Usual warning about using 'string1' in 'string2': 'name' in 'enamel' is True, 'hello' in 'Othello' is True, etc., but obviously you can make the condition arbitrarily complicated.)
You could use a regex and then replace the text.
import re
c = "This is a file's contents, apparently you want to insert text"
re.sub('text', 'text here', c)
print c
returns "This is a file's contents, apparently you want to insert text here"
Not sure if it'll work for your usecase but it's nice and simple if it fits.
This will look for any string, in the file (not specific, to be at the start of the line only, i.e. can exist spread over multiple lines as well).
Typically you can follow the algo as:
lookup for the string in the file, and capture "location"
then split the file about this "location", and attempt to create new files as
write start-to-loc content to new file
next, write your "NEW TEXT" to the new file
next, loc-to-end content to new file
Let us see code:
#!/usr/bin/python
import os
SEARCH_WORD = 'search_text_here'
file_name = 'sample.txt'
add_text = 'my_new_text_here'
final_loc=-1
with open(file_name, 'rb') as file:
fsize = os.path.getsize(file_name)
bsize = fsize
word_len = len(SEARCH_WORD)
while True:
found = 0
pr = file.read(bsize)
pf = pr.find(SEARCH_WORD)
if pf > -1:
found = 1
pos_dec = file.tell() - (bsize - pf)
file.seek(pos_dec + word_len)
bsize = fsize - file.tell()
if file.tell() < fsize:
seek = file.tell() - word_len + 1
file.seek(seek)
if 1==found:
final_loc = seek
print "loc: "+str(final_loc)
else:
break
# create file with doxygen comments
f_old = open(file_name,'r+')
f_new = open("new.txt", "w")
f_old.seek(0)
fStr = str(f_old.read())
f_new.write(fStr[:final_loc-1]);
f_new.write(add_text);
f_new.write(fStr[final_loc-1:])
f_new.close()
f_old.close()

Categories

Resources