I'm making a small program to trace the execution flow of a program. I have some files that have source code and some that don't. For calls that happen in files without source, I'm trying to count them and tack that number to the end of the output line.
From what I understand I'm positioning the cursor 3 characters from the end and then when I write output to myfile, it should have overwritten the previous 3 characters. But when I look in the file, those 3 characters are just getting appended to the end.
with open("C:\\Windows\\Temp\\trace.html", "a+") as myfile:
if hasNoSource and not fileHasChanged:
myfile.seek(-3,2)
output = line
else:
self.noSourceCallCount = 0
myfile.write(output)
return self.lineHook
"a+" mode is open for append mode and any changes by seek() will be reset by next write(). Use "r+" mode.
fileinput module with the inplace option allows you to modify your file but be sure to make a backup if all hell break loose
import fileinput,sys,re
line_count=0
for line in open(my_file):
line_count+=1 # count total lines in file
f=fileinput.input(my_file,inplace=True)
for line in f:
line_count-=1 #when iterating through every line decrement line_count by 1
if line_count==0:
line=re.sub("...$",<replacement>,line) #use regex to replace first three characters in the last line
sys.stdout.write(line) #print line to sys.stdout which will automatically make the changes to this line in file.
else:
sys.stdout.write(line)
Related
I am working in Julia 1.4. I would like to open two large gzipped files (file1.gz and file2.gz) and then read the first line from file 1, the first line from file 2, do something with these, and then move on to the second line of each file etc.
If I nest two for loops, this obviously does not work because it cycles through file2 before moving on to the next line of file1. The files are two big to open all at once.
handle1 = GZip.open(file1.gz)
handle2 = GZip.open(file2.gz)
for line1 in eachline(handle1)
for line2 in eachline(handle2)
println(line1,line2)
end
end
Is there a simple solution ?
Yes, you can use zip. You can also manage the eachline iterators yourself, but using zip is easier:
handle1 = GZip.open(file1.gz)
handle2 = GZip.open(file2.gz)
for (line1, line2) in zip(eachline(handle1), eachline(handle2))
println(line1,line2)
end
close(handle1)
close(handle2)
Don't forget to close your files!
Also, do note that if the two files have a different number of lines, the zip iterator will stop when the first of the two files runs out.
So, I am essentially just dreaming up ideas right now.
I was wondering if it was possible to make a python program that can read a document, take a line from the document, make an if/else statement with it (Like if the text on that line is equal to Hello, than say hello back), and then continue onto the next line. I have already kind of done this in a shell fashion but I want to see if it is possible to have python read the line of a document, interpret it, display something, and move on to the next line of the document.
(I am prepared for this post to get tons of -1's for not knowing how to program a lot of python, and probably just not being clear enough. So before you -1, just add a comment saying what you need me to be clear about.)
The version of python of my choice would be 2.5.
Since you don't know any Python, try this:
with open("file.txt") as f:
for line in f:
if line.strip() == "Hello":
print "Hello back"
or without the exception-safe clause:
for line in open("file.txt"):
if line.strip() == "Hello":
print "Hello back"
the strip() removes the ending newline \n from the line
That is actually a very simple task in Python:
file = open("file.txt") # open the file
while True:
word = file.readline() # read a line from the file
print word # print it to the console
if word == "": # if out of words...
file.close() # ...close the file
break # and break from while loop and exit program
I would like to be able to save the TEXT output of an iPython notebook cell into a file on disk.
I have 2 additional requirements/requests:
be able to re-run the cell and overwrite my output with whatever the latest is.
also display the output within the notebook.
I have figured out how to use the %%capture magic for some basic saving of an iPython notebook's cell into a file, but it does not seem flexible enough: it keeps appending every time I re-run the cell and I cannot get it to display within the same cell.
Here is what I have so far:
%%capture cap --no-stderr
print 'stuff'
with open('output.txt', 'w') as f:
f.write(cap.stdout)
# clear the cap by deleting the variable here?
# del cap
When I try to put cap.show() after the write, it does not seem to display. Instead, it puts the output into the cap variable twice.
You have a typo, missing d in cap.stout. It should be cap.stdout
I tested the following and it worked fine. cap.show() also printed "stuff" and re-running the cell overwrote the file.
%%capture cap --no-stderr
print 'stuff'
with open('output.txt', 'w') as f:
f.write(cap.stdout)
%%capture cap --no-stderr
print("a")
with open('output.txt', 'w') as f:
f.write(str(cap))
I wrote a script that executes commands in parallel. I let them all write an entry to the same log file. It does not matter if the order is wrong or entries are interleaved, but i noticed that some entries are missing. I should probably lock the file before writing, however, is it true that if multiple processes try to write to a file simultaneously, it will result in missing entries?
Yes, if different processes independently open and write to the same file, it may result in overlapping writes and missing data. This happens because each process will get its own file pointer, that advances only by local writes.
Instead of locking, a better option might be to open the log file once in an ancestor of all worker processes, have it inherited across fork(), and used by them for logging. This means that there will be a single shared file pointer, that advances when any of the processes writes a new entry.
In a script you should use ">> file" (double greater than) to append output to that file. The interpreter will open the destination in "append" mode. If your program also wants to append, follow the directives below:
Open a text file in "append" mode ("a+") and give preference to printing only full lines (don't do multiple 'print' followed by a final 'println', but print the entire line with a single 'println').
The fopen documentation states this:
DESCRIPTION
The fopen() function opens the file whose pathname is the
string pointed to by filename, and associates a stream with
it.
The argument mode points to a string beginning with one of
the following sequences:
r or rb Open file for reading.
w or wb Truncate to zero length or create file
for writing.
a or ab Append; open or create file for writing
at end-of-file.
r+ or rb+ or r+b Open file for update (reading and writ-
ing).
w+ or wb+ or w+b Truncate to zero length or create file
for update.
a+ or ab+ or a+b Append; open or create file for update,
writing at end-of-file.
The character b has no effect, but is allowed for ISO C
standard conformance (see standards(5)). Opening a file with
read mode (r as the first character in the mode argument)
fails if the file does not exist or cannot be read.
Opening a file with append mode (a as the first character in
the mode argument) causes all subsequent writes to the file
to be forced to the then current end-of-file, regardless of
intervening calls to fseek(3C). If two separate processes
open the same file for append, each process may write freely
to the file without fear of destroying output being written
by the other. The output from the two processes will be
intermixed in the file in the order in which it is written.
It is because of this intermixing that you want to give preference to
using only 'println' (or its equivalent).
I'm learning the Flex command-line debugger, and I haven't been able to find information on this particular use case.
I'd like to add a breakpoint to a specific line in one of my class files. I can add breakpoints at the start of a function in a class, but I can't figure out how to set it at a specific line (e.g. line 117 in Foo.as)?
When I try to set one for a file on a given line, I get one at a different location:
(fdb) break Foo 111
Breakpoint 1 at 0x######: file Foo.as, line 115
I've verified the line # I'm specifying is valid, so I don't think the FDB is trying to compensate.
Am I doing something wrong? Is this possible in FDB?
Abso-lutely,
check out the help in fdb, it's fairly helpful :). Just type help or type help then a command. help break gives the output below, lots of nice ways to hook in there, the syntax your using is just missing a colon in between the class and the line number specified, just tried with an MXML file and it worked fine.
Set breakpoint at specified line or function.
Examples:
break 87
Sets a breakpoint at line 87 of the current file.
break myapp.mxml:56
Sets a breakpoint at line 56 of myapp.mxml.
break #3:29
Sets a breakpoint at line 29 of file #3.
break doThis
Sets a breakpoint at function doThis() in the current file.
break myapp.mxml:doThat
Sets a breakpoint at function doThat() in file myapp.mxml.
break #3:doOther
Sets a breakpoint at function doOther() in file #3.
break
Sets a breakpoint at the current execution address in the
current stack frame. This is useful for breaking on return
to a stack frame.
To see file names and numbers, do 'info sources' or 'info files'.
To see function names, do 'info functions'.
Abbreviated file names and function names are accepted if unambiguous.
If line number is specified, break at start of code for that line.
If function is specified, break at start of code for that function.
See 'commands' and 'condition' for further breakpoint control.