how to log the execution in python - python-3.x

I have a python script containing a function to sum of two number.I want to create a logfile which logs everything during execution.How should I do that?Could you please explain with some example?
def sum(a,b):
retrun a + b
a = sum(10,20)

You can create a simple log file by,
Opening a file at a known location with proper access mode e.g. filehandle = open(Logfilefullpath, "a+") - Opening in append mode.
Use the write function to log your required information to the file. e.g. filehandle.write("sum function... ")
Close the filehandle to release the file. e.g. filehandle.close()

Related

Is there a way to directly edit a certain text file line through the OS module? (Python 3.7)

I am trying to make a game, where your score saves as a text file. The score (clicks) must always be on the second line and save per user. Every time a user saves, I would like the second line of the text file to be replaced with the new score.
I have tried using loads of things suggested on stack overflow, like the os.replace or os.resub, but none work.
def save():
global userlog
global clicks
score = open(directory + "/" + userlog + ".txt", "r+")
#### On this line, I want some code that will replace the second line in the text file listed above.
for i in range(random.randint(2,5)):
print("Saving")
time.sleep(0.10)
print("Saving.")
time.sleep(0.10)
print("Saving..")
time.sleep(0.10)
print("Saving...")
time.sleep(0.10)
print("\nGame Saved Sucessfully!")
I have not had anything work. Just getting some standard error messages.
Any help will be appreciated :)
Thanks :)
an illustration of my comment - your save function could do something like
# load previously logged information
with open(logfile, 'r') as fobj:
log = fobj.readlines()
# replace line 2 with some new info
log[1] = 'some new info\n'
# overwrite existing logfile
with open(logfile, 'w') as fobj:
for line in log:
fobj.write(line)
In principle you could also use open() in r+ mode as you wrote in the question. That would require you to use seek() (see e.g. here) to get the file pointer to the position you want to write at - a more complicated option which I would not recommend.

How to get the result values appended to an CSV file in jmeter(groovy)

I am getting a value from HTTP request which I am writing it into a CSV file, each and every time when the program is executed, the new values are overwritten and not appended to the CSV. I would like to append the values instead of overwriting. I am using Regex and XPath extractor to get the values from the HTTP requests and writing it an CSV file.
new File('/Users/ddd/testgui/queueId1.csv').newWriter().withWriter { w ->
w << vars.get('queueid')
}
So this works for me, on groovysh 2.5.3 :
new File('/Users/ddd/testgui/queueId1.csv').newWriter(true).withWriter { w ->
w << vars.get('queueid')
}
The true in the newWriter is for append == true.
You can do just:
new File('/Users/ddd/testgui/queueId1.csv') << vars.get('queueid')
Be aware that your code is going to work fine only when you have 1 thread, if there will be more - you may suffer from a race condition when 2 threads will be simultaneously writing into a file.
If you're going to execute this code with > 1 virtual user I would rather recommend going for Sample Variables functionality.
If you add the next line to user.properties file:
sample_variables=queueid
and restart JMeter to pick the property up next time you run your test the .jtl results file will have an extra column with queueid variable value for each thread/request.
If you want to store it into a separate file - go for Flexible File Writer

Opening another .py file in a function to pass agruments in Python3.5

I'm pretty new to Python and the overall goal of the project I am working on is to setup a SQLite DB that will allow easy entries in the future for non-programmers (this is for a small group of people who are all technically competent). The way I am trying to accomplish this right now is to have people save their new data entry as a .py file through a simple text editor and then open that .py file within the function that enters the values into the DB. So far I have:
def newEntry(material=None, param=None, value=None):
if param == 'density':
print('The density of %s is %s' % (material, value))
import fileinput
for line in fileinput.input(files=('testEntry.py'))
process(line)
Then I have created with a simple text editor a file called testEntry.py that will hopefully be called by newEntry.py when newEntry is executed in the terminal. The idea here is that some user would just have to put in the function name with the arguments they are inputing within the parentheses. testEntry.py is simply:
# Some description for future users
newEntry(material='water', param='density', value='1')
When I run newEntry.py in my terminal nothing happens. Is there some other way to open and execute a .py file within another that I do not know of? Thank you very much for any help.
Your solution works, but as a commenter said, it is very insecure and there are better ways. Presuming your process(...) method is just executing some arbitrary Python code, this could be abused to execute system commands, such as deleting files (very bad).
Instead of using a .py file consisting of a series of newEntry(...) on each line, have your users produce a CSV file with the appropriate column headers. I.e.
material,param,value
water,density,1
Then parse this csv file to add new entries:
with open('entries.csv') as entries:
csv_reader = csv.reader(entries)
header = True
for row in csv_reader:
if header: # Skip header
header = False
continue
material = row[0]
param = row[1]
value = row[2]
if param == 'density':
print('The density of %s is %s' % (material, value))
Your users could use Microsoft Excel, Google Sheets, or any other spreadsheet software that can export .csv files to create/edit these files, and you could provide a template to the users with predefined headers.

Overwriting specific lines in Python

I have a simple program that manipulates some stored data on some text files. However I have to store the name and the password on different files for python to read.
I was wondering if I could get these two words (The name and the password) on two separate lines on one file and get python to overwrite just one of the lines based on what I choose to overwrite (either the password or the name).
I can get python to read specific lines with:
linenumber=linecache.getline("example.txt",4)
Ideally id like something like this:
linenumber=linecache.writeline("example.txt","Hello",4)
So this would just write "Hello" in "example.txt" only on line 4.
But unfortunately it doesn't seem to be as simple as that, I can get the words to be stored on separate files but overall doing this on a larger scale, I'm going to have a lot of text files all named differently and with different words on them.
If anyone would be able to help, it would be much appreciated!
Thanks, James.
You can try with built in open() function:
def overwrite(filename,newline,linenumber):
try:
with open(filename,'r') as reading:
lines = reading.readlines()
lines[linenumber]=newline+'\n'
with open(filename,'w') as writing:
for i in lines:
writing.write(i)
return 0
except:
return 1 #when reading/writing gone wrong, eg. no such a file
Be careful! It is writing all the lines all over again in a loop and when it comes to exception example.txt may already be blank. You may want to store all the lines in list all the time to write them back to file in exception. Or keep backup of your old files.

Loading a string in a variable instead of the name of the variable (R)

I am trying to load data frames that are saved in a certain folder. I have a bash script that loops along all *.gzip files in the folder and passes the file names as arguments to an R script (blah.r $file_name). Now, in the R script, the file name is saved as
file_name = commandArgs(TRUE)[1]
and it prints the correct file name. However, when I try to load the file
data(file_name)
R thinks that file_name is a string, not a variable, so it says that it can't find "file_name".
How can I get R to recognize this variable as a variable and not a literal string?
The Answer to this the question asked is along the lines of
read.table(file = file_name, ....)
where .... are additional arguments to specify the nature of the text file containing the data you wish to load.
If the data are not in a text file but in some other, possibly binary, format then you will need to use the correct function to import those data. For example, if the data are stored in one of R's formats (via save() or saveRDS()) then:
load(file = file_name) ## for save()-ed objects
foo <- readRDS(file = file_name) ## for objects serialised via saveRDS()
You mention the files are *.gzip. If so, then see ?connections and the gzip() function, which can also be passed an object containing the file name to open as in:
gzip(file_name, ....)
where .... again are further arguments you may need to specify (read the help page).

Resources