i make a simple code in python to output data in txt format file in my local driver pc using windows OS but nothing happened . i want to know the problem
here is the code :
f = open("my.txt" , "w")
def a():
return (2+3)
def x():
b = a()
print("\n" ,b)
f.write(x())
f.close()
please try this
f = open("my.txt" , "w")
def a():
return (2+3)
def x():
b = a()
print("\n" ,b)
return str(b)
f.write(x())
f.close()
since function x does not return anything you cant print it to file
Writing into files both strings and variables.
Please Note: There are many ways to get it done. This is just one.
#!/usr/bin/env python
import sys
# function returning compute results
def fun_compute(num):
return num * num
# For writing in a file.
# Opened the file in w+ mode
with open("./files/sample.txt", "w+") as sys.stdout:
print("I am printing fun stuff!") # writing standard string
num = 5
for n in range(num):
print("fun_compute for - %s" % fun_compute(n))
Related
I would like to rename the file according to several examples.
My idea is by using a list such as(example):
a = [1,2,3,4,5,6,7,8,10, 100, 200]
Then loop into this list and rename based on each of the element within the list.
My code is as follow (This is an example of the code and not the full version, I just want to get to know a way to input these element into the "**" and replace it with value such as "1", "2" or "100"):
class man:
...
def function(a):
...
def output1(myfile):
with open("text_**.txt","w+") as outfile:
outfile.write()
def output2(myfile2):
with open("text_**.txt","w+") as outfile:
outfile.write()
def total(a,b):
with open("text_**.txt","w+") as outfile:
outfile.write()
if __name__ == "__main__":
file = function("**.txt")
...
output1(myfile)
output2(myfile2)
total("**.txt", "**.txt")
For example, I would like my output to be like this:
class man:
...
def function(a):
...
def output1(myfile):
with open("text_1.txt","w+") as outfile:
outfile.write()
def output2(myfile2):
with open("text_1.txt","w+") as outfile:
outfile.write()
def total(a,b):
with open("text_1.txt","w+") as outfile:
outfile.write()
if __name__ == "__main__":
file = function("1.txt")
...
output1(myfile)
output2(myfile2)
total("1.txt", "1.txt")
My goal is the "**" will be replace with all the elements within the list from 1 to 200. If possible to make it this way then I wouldnt need to keep changing the value in my program everytime I want to load new name for it.
Okay,
I suppose you could use an environment variable for this.
import os
counter = os.environ.get('MY_FILE_COUNTER')
if counter is None:
os.environ['MY_FILE_COUNTER'] = 1
else:
os.environ['MY_FILE_COUNTER'] += 1
# do your stuff
Or you could save the current value in a text file and load it up before processing your stuff
I'm trying to write a export to file function in Python. Here's a snippet:
#!/usr/bin/env python
def function_1(x):
for i in range(len(x)):
ip = packet[i]
mac = mac[i]
print '{}, {}'.format(ip, mac)
def export()
f=open("data.txt", "w")
f.write() #f.write(function_1(x))??
f.close()
if __name__ == "__main__":
function_1(10)
export()
I can do write to a file by putting it in the same function as function_1, but how would I do it in another function? Do I need to return?
Yes, f.write needs a string for input. The easiest way is to create the string directly in your function and return it:
def function_1(x):
ret_val = ""
for i in range(len(x)):
ip = packet[i]
mac = mac[i]
ret_val += '{}, {}\n'.format(ip, mac)
return ret_val
I've made a function for a flask application to create a decorator and a function and then write them to a file but when I run it, it doesn't create a file and write to it and it doesn't return any errors.
def make_route(title):
route = "#app.route(/%s)" %(title)
def welcome():
return render_template("%s.html" %(title))
return welcome
f = open('test1.txt', 'w')
f.write(route, '/n', welcome, '/n')
f.close()
make_route('Hi')
A return statement terminates execution of the function, so any code after it is ignored. Also, write writes a string, not random objects. You want:
def make_route(title):
route = "#app.route(/%s)" %(title)
def welcome():
return render_template("%s.html" %(title))
with open('test1.txt', 'w') as f:
f.write('%r\n%r\n' % (route, welcome))
return welcome
make_route('Hi')
I would use philhag answer but use %s instead of %r or you'll write a string, and you could use .name if you want to use the function more than once(Which you probably do).
def make_route(title):
route = "#app.route('/%s')" %(title)
def welcome():
return render_template("%s.html" %(title))
with open('test2.py', 'w') as f:
f.write('%s\n%s\n' % (route, welcome))
welcome.__name__ = title
return welcome
make_route('Hi')
I am trying to write a decorator that adds verbose logging to a function via a decorator (a method would be nice too, but I haven't tried that yet). The motivation behind this is that patching in a one-line add_logs decorator call into a box in production is much easier (and safer) than adding 100 debug lines.
Ex:
def hey(name):
print("Hi " + name)
t = 1 + 1
if t > 6:
t = t + 1
print("I was bigger")
else:
print("I was not.")
print("t = ", t)
return t
I'd like to make a decorator that will transform this into code that does this:
def hey(name):
print("line 1")
print("Hi " + name)
print("line 2")
t = 1 + 1
print("line 3")
if t > 6:
print("line 4")
t = t + 1
print("line 5")
print("I was bigger")
else:
print("line 6")
print("I was not.")
print("line 7")
print("t = ", t)
print("line 8")
return t
What I've got so far:
import inspect, ast
import itertools
import imp
def log_maker():
line_num = 1
while True:
yield ast.parse('print("line {line_num}")'.format(line_num=line_num)).body[0]
line_num = line_num + 1
def add_logs(function):
def dummy_function(*args, **kwargs):
pass
lines = inspect.getsourcelines(function)
code = "".join(lines[0][1:])
ast_tree = ast.parse(code)
body = ast_tree.body[0].body
#I realize this doesn't do exactly what I want.
#(It doesn't add debug lines inside the if statement)
#Once I get it almost working, I will rewrite this
#to use something like node visitors
body = list(itertools.chain(*zip(log_maker(), body)))
ast_tree.body[0].body = body
fix_line_nums(ast_tree)
code = compile(ast_tree,"<string>", mode='exec')
dummy_function.__code__ = code
return dummy_function
def fix_line_nums(node):
if hasattr(node, "body"):
for index, child in enumerate(node.body):
if hasattr(child, "lineno"):
if index == 0:
if hasattr(node, "lineno"):
child.lineno = node.lineno + 1
else:
# Hopefully this only happens if the parent is a module...
child.lineno = 1
else:
child.lineno = node.body[index - 1].lineno + 1
fix_line_nums(child)
#add_logs
def hey(name):
print("Hi " + name)
t = 1 + 1
if t > 6:
t = t + 1
print("I was bigger")
else:
print("I was not.")
print("t = ", t)
return t
if __name__ == "__main__":
print(hey("mark"))
print(hey)
This produces this error:
Traceback (most recent call last):
File "so.py", line 76, in <module>
print(hey("mark"))
TypeError: <module>() takes no arguments (1 given)
which makes sense because compile creates a module and of course modules are not callables. I've tried a hundred different ways of making this work at this point but can't come up with a working solution. Any recommendations? Am I going about this the wrong way?
(I haven't been able to find a tutorial for the ast module that actually modifies code at runtime like this. A pointer to such a tutorial would be helpful as well)
Note: I am presently testing this on CPython 3.2, but a 2.6/3.3_and_up solution would be appreciated. Currently the behavior is the same on 2.7 and 3.3.
When you compile the source, you get a code object representing a module, not a function. Substituting this code object into an existing function won't work, because it's not a function code object, it's a module code object. It's still a code object, though, not a real module, you so can't just do hey.hey to get the function from it.
Instead, as described in this answer, you need to use exec to execute the module's code, store the resulting objects in a dictionary, and extract the one you want. What you could do, roughly, is:
code = compile(ast_tree,"<string>", mode='exec')
mod = {}
exec(code, mod)
Now mod['hey'] is the modified function. You could reassign the global hey to this, or replace its code object.
I am not sure if what you're doing with the AST is exactly right, but you will need to do the above at any rate, and if there are problems in the AST manipulation, doing this will get you to a point where you can start to debug them.
It looks like you're trying to hackily implement a trace function. Can I suggest using sys.settrace to accomplish that in a more reusable fashion?
import sys
def trace(f):
_counter = [0] #in py3, we can use `nonlocal`, but this is compatible with py2
def _tracer(frame, event, arg):
if event == 'line':
_counter[0] += 1
print('line {}'.format(_counter[0]))
elif event == 'return': #we're done here, reset the counter
_counter[0] = 0
return _tracer
def _inner(*args, **kwargs):
try:
sys.settrace(_tracer)
f(*args, **kwargs)
finally:
sys.settrace(None)
return _inner
#trace
def hey(name):
print("Hi " + name)
t = 1 + 1
if t > 6:
t = t + 1
print("I was bigger")
else:
print("I was not.")
print("t = ", t)
return t
hey('bob')
Output:
$ python3 test.py
line 1
Hi bob
line 2
line 3
line 4
I was not.
line 5
t = 2
line 6
Note that the semantics of this are slightly different than in your implementation; the if branches not exercised by your code, for example, are not counted.
This ends up being less fragile - you're not actually modifying the code of the functions you're decorating - and has extra utility. The trace function gives you access to the frame object before executing each line of code, so you're free to log locals/globals (or do some dodgy injection stuff, if you're so inclined).
When you call inspect.getsource() with a decorated function, you also get the decorator, which, in your case, gets called recursively (just twice, and the second time it produces an OSError).
You can use this workaround to remove #add_logs line from the source:
lines = inspect.getsourcelines(function)
code = "".join(lines[0][1:])
EDIT:
It looks like your problem is that your dummy_function doesn't take arguments:
>>> print(dummy_function.__code__.co_argcount)
0
>>> print(dummy_function.__code__.co_varnames)
()
Whereas your original function does:
>>> print(hey.__code__.co_argcount)
1
>>> print(hey.__code__.co_varnames)
('name')
EDIT:
You're right about the code object being returned as a module. As pointed in another answer, you have to execute the this object and then, assign the resulting function (identifiable by function.__name__) to dummy_function.
Like so:
code = compile(ast_tree,"<string>", mode='exec')
mod = {}
exec(code, mod)
dummy_function = mod[function.__name__]
return dummy_function
Then:
>>> print(hey('you'))
line 1
Hi you
line 2
line 3
I was not.
line 4
t = 2
line 5
2
Is there a way to save data after it was printed to the screen?
for example:
lets have some arbitrary function
def main():
if something:
for i in range(n):
output= "%f %f" %(n,d)
print output
if something:
for i in range(n):
output="%f %f" %(n,d)
print output
fileout=open("data.csv", "a")
fileout.write(output)
this will only write the last data for the last range in for loop.
Edit: I want to ask a user if she/he wants to save that data
Declare your output variable(s) at the highest level of scope in your program first. This will allow it to be written to a file in the manner you've programmed.
If you want to prompt a user for a location to save the file(s), that's merely this:
out1 = raw_input("Where would you like to save this? ")
You can do the same for another output file variable.
just use this in the if conditions:
print >>fileout, output #this will save the output to the data.csv file
Change your code...
1: If you really want to use print, change sys.stdout to a different stream
2: use files
1
import sys
oldstdout=sys.stdout
f=open("myfile","w")
sys.stdout=f
def main():
if something:
for i in range(n):
print "%f %f"%(n,d)
if something:
for i in range(n):
print "%f %f"%(n,d)
2
f=open("myfile","w")
def main():
if something:
for i in range(n):
f.write("%f %f"%(n,d))
if something:
for i in range(n):
f.write("%f %f"%(n,d))
Here is a (somewhat pathological) example that will let you both print and save the statements that you print in a global list (which we'll call OUTPUT):
import sys
OUTPUT = []
def print_wrapper(method):
class result(object):
def __init__(self, file_obj):
self.file_obj = file_obj
def __getattr__(self, name):
return getattr(self.file_obj, name)
def write(self, value):
OUTPUT.append(value)
return self.file_obj.write(value)
return result(method)
original_stdout = sys.stdout
sys.stdout = print_wrapper(original_stdout)
# This will still print, but will add 'Hi' and '\n' to OUTPUT as well
print 'Hi'
# This will still print, but will add 'None' and '\n' to OUTPUT as well
print None
# This uses the original stdout to print, so won't change OUTPUT
original_stdout.write(repr(OUTPUT))
original_stdout.write('\n')
or you could alternately prepare yourself for Python 3 (or just use it) and wrap the print method itself:
from __future__ import print_function # must have Python >= 2.6
OUTPUT = []
def wrap_print(method):
def result(value):
OUTPUT.append(value)
return method(value)
return result
old_print = print
print = wrap_print(old_print)
print('Hi')
print(None)
old_print(OUTPUT)