You can try
hr, sc = divmod(counter, 3600)
mn, sc = divmod(sc, 60)
msg = '%d hours, %d minutes and %d seconds' % (hr, mn, sc)
print(msg)
You can try
hr, sc = divmod(counter, 3600)
mn, sc = divmod(sc, 60)
msg = '%d hours, %d minutes and %d seconds' % (hr, mn, sc)
print(msg)
It is possible for global variables
>>> varname = 'thevalue'
>>> globals()[varname] = 3.14
>>> thevalue
3.14
In principle it doesn't work for local variables. Dictionaries returned by locals()
are read-only.
In your example, x == y == -1.0
. The vector (-1.0, -1.0)
makes an angle of -135.0
degrees with the horizontal axis, and not 45.0
degrees. So math.atan2()
is correct.
If no line of /Users/some_user/Desktop/passwords.txt contains a colon, your program won't print any output. Add a call to print() for every line in the loop.
Edit: I just noticed the call to readline(). It reads only a single line. Use readlines().
Please why I get this error when I run my code?
Don't call your file crypt.py if it is importing a module named crypt. Remove any file crypt.py or crypt.pyc from your folder.
It is already efficient (1.6 microseconds on my computer)
>>> from timeit import Timer
>>> L = [1,2,3,4,5,6,7,8,9,10]
>>> # run your statement 1 million times
>>> Timer("sum([(i) for i in L if i%2 ==0])", "from __main__ import L").timeit()
1.607414960861206
>>> # removing the inner list construction is surprisingly less efficient
>>> Timer("sum(i for i in L if i%2 ==0)", "from __main__ import L").timeit()
1.9511890411376953
>>> # gain a little by avoiding the modulo operator
>>> Timer("sum([i for i in L if not (i & 1)])", "from __main__ import L").timeit()
1.4257829189300537
You can download one here, called pydrawing, which claims to draw diagrams in a tkinter canvas.
Python and tkinter have been around for 20 years, which means many attempts to write paint programs. There is a basic example in Mark Lutz' book 'programming python'.
The first step in your project is to crawl the web ;)
Use the Command class in this code snippet to get your shell command's output
com = Command(zip_command).run()
print(com.output)
print(com.error)
if com.failed:
print('BACKUP FAILED!')
else:
print('Successful backup to ' + target)
os.system()
is deprecated in favor of the subprocess
module.
You may also consider using module zipfile
instead of an external command.
You can use the re
module
>>> import re
>>> string = "hello world!"
>>> result = re.sub(r'\s+', ' ', string)
>>> print(result)
hello world!
Another way is to split and join
>>> result = ' '.join(string.split())
>>> print(result)
hello world!
You could probably use a non blocking input with a call to select() like in this example (linux only):
#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import unicode_literals, print_function, division
__doc__ = """ module: sandbox.pollinput -
"""
import select
import sys
import time
def opt_input():
i, w, x = select.select([sys.stdin], [], [], 0)
if i:
return sys.stdin.readline()
else:
return ''
def prompt():
sys.stdout.write('Phrase: ')
sys.stdout.flush()
def main():
prompt()
while True:
input_value = opt_input() # non blocking attempt
if input_value.strip() == 'stop':
sys.exit(0)
else:
if input_value:
prompt()
time.sleep(0.3) # <-- simulate program busy
if __name__ == "__main__":
main()
Well, it looks like
class A(object): # <--- small 'c'
def __init__(self):
self.a = 4 # <--- a and b are instance variables (not class variables)
self.b = 6
class B(A):
def __init__(self): # <--- watch the number of underscores
A.__init__(self) # <--- call parent class constructor explicitely
#some code
def Action(self):
self.a = 9 # <--- update member a
Then try subprocess.Popen("open /Applications/Snes9x.app", shell=True)
Permission denied means that the user who is running your python program doesn't have the permission to list the directory, or to run Snes9x, or that Snes9x is not an executable program, etc. It is a system issue, not a python issue.
Use the subprocess module
process = subprocess.Popen('Snes9x', shell = True)
Use len(list(combinations(numbers, 6)))
The interpreter only obeys python's grammar which says that both sides of a comparison operator must be "or_expr"s (one of python's syntactic categories). An expression like not ...
can not be considered an or_expr. With parenthesis, it becomes an "atom", which can be considered as an "or_expr".
Grammar is a cold mechanism, don't think python does anything clever here :)
There is no problem in jumping back and forth if you do it through class instances, for example in module A
# mod A
from B import foo
class Bar(object):
def baz(self):
print("qux")
x = Bar()
foo(x) # call function foo from module B
and in module B
# mod B
def foo(bar):
bar.baz() # call method .baz() defined in module A
Notice that module B uses module A features without importing anything from A.
os.getenv('PATH')
is the sequence of folders where the operating system finds executable programs. sys.path
is the sequence of folders where python finds importable modules.
I also want to remove header line (first line) and want to catenate rest of the lines.
This code removes the first line of a file and prints the rest, concatenated
whith open("myfile.txt", "rb") as ifh:
next(ifh) # skip first line
print(''.join(x.rstrip('\n') for x in ifh)) # read the rest, concatenate and print
This deserves an answer:
''' tk_button_toggle5.py
'''
from functools import partial
import itertools
import sys
python2 = sys.version_info[0] == 2
tk = __import__("tT"[python2] + "kinter")
def toggle(button):
button.state = not button.state
button['text'] = str(button.state)
def new_btn(state):
btn = tk.Button(width=12)
btn.state = bool(state)
btn.config(text= str(btn.state), command = partial(toggle, btn))
btn.pack(pady=5)
return btn
root = tk.Tk()
for x in (1, 0, 1):
new_btn(x)
root.mainloop()
Notice that btn.state
can now be accessed directly.
There is something strange in this code
>>> 'easyhint' < 8
False
You are comparing constant strings to integers. You probably meant something else. This needs to be corrected.
but i wanted to learn re module...
You can start with the chapter about the re module in diveintopython.
The first rule is always use raw strings for regular expressions, eg re.compile( r"foo" )
(notice the r).
I'm not (yet) a specialist of web frameworks in python, but yes, one of the purposes of templating systems is to mix html code and python code. The main idea is to write html files containing python expressions and blocks of code with a special markup syntax. This file is called the template. The templating system provides a render()
method which evaluates the template in a certain python context, and you can output the resulting html.
If you want a powerful and simple templating system, try Mako which benefits from the experience of many other python templating engines developped in the last 15 years. Among other things, mako templates can be compiled into python modules for performance. They also implement an inheritance system between templates see here. I think this templating system can very well be used with web.py or other frameworks.
Another nice feature of mako templates is that they can be used for completely different purposes. For example I use them to produce restructured text files, post-processed by rstex and latex to write scientific papers.
Well, here is how to read it with the csv module
#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import unicode_literals, print_function, division
from collections import namedtuple
import csv
csv.register_dialect('bookdialect',
delimiter = str(','),
quoting = csv.QUOTE_ALL,
doublequote = False,
quotechar = str('"'),
escapechar = str('\\'),
)
record = namedtuple("record", "name phmobile phhome company email phcompany fax birthday")
with open("book.csv", "rb") as ifh:
reader = csv.reader(ifh, dialect = 'bookdialect')
records = list(record(*(x.strip() for x in row)) for row in reader)
print(records)
print("="*20)
print(records[3])
print("="*20)
print(records[4].name, records[4].phhome, records[4].email)
"""my output -->
[record(name='First Name', phmobile='Mobile Phone', phhome='Home Phone', company='Company', email='E-mail Address', phcompany='Company Main Phone', fax='Business Fax', birthday='Birthday'), record(name='121', phmobile='121', phhome='', company='', email='', phcompany='', fax='', birthday=''), record(name='Abha Garg', phmobile='08600746256', phhome='', company='', email='', phcompany='', fax='', birthday=''), record(name='Bakh Bagla(a G)', phmobile='+91932424617', phhome='', company='', email='', phcompany='0188424242', fax='', birthday=''), record(name='Dad', phmobile='+91945334045', phhome='+9188743428', company='', email='eresfsfdra@yrdl.com', phcompany='+91353423449', fax='', birthday=''), record(name='tailor master', phmobile='9357310498', phhome='', company='', email='', phcompany='', fax='', birthday=''), record(name='taruna', phmobile='09015561619', phhome='+918968391049', company='', email='tarunthegreat43@gmail.com', phcompany='', fax='', birthday=''), record(name='Kanika Jain TL@ Pf', phmobile='9967504886', phhome='', company='', email='', phcompany='', fax='', birthday=''), record(name='', phmobile='+918968554786', phhome='', company='', email='', phcompany='', fax='', birthday=''), record(name='', phmobile='9167228454', phhome='', company='', email='', phcompany='', fax='', birthday=''), record(name='VAS Act/Deact', phmobile='12116', phhome='', company='', email='', phcompany='', fax='', birthday='')]
====================
record(name='Bakh Bagla(a G)', phmobile='+91932424617', phhome='', company='', email='', phcompany='0188424242', fax='', birthday='')
====================
Dad +9188743428 eresfsfdra@yrdl.com
"""
There are also solutions if the file is encoded in unicode.
If it is a csv file, it would be easier to read with the csv module. You would select the first entry of each row to get the first name. Can you post a few rows of your file (with real names and addresses replaced by similar fancy data) ?
You should have a look in numpy masked arrays. I can not help you much here, because I never tried it.
The only thing you need to do is determine which lists you want to append to Resistance. For example if you want to append the values from a column numbered k, you can write
def column_values(rows, k):
for row in rows:
yield row[k]
rows = list(Reader) # convert to list in case Reader is a generator.
Resistance.append(list(to_float(column_values(rows, 0))))
Well, here is something which should always work
def to_float(sequence):
"""Generate a sequence of floats by converting every item in
a given sequence to float, and ignoring failing conversions"""
for x in sequence:
try:
yield float(x)
except ValueError:
pass
Now if you want to append all the values in columns 4, 5, ... for all rows,
you can write a generator
def sheet_values(reader):
"""Generate the cell values that we want to convert and append to Resistance"""
for row in reader:
for x in row[4:]:
yield x
Finally, here is how to append all the values
Resistance.append(list(to_float(sheet_values(Reader)))
Perhaps you could describe what is this variable Resistance. Is it a list, a list of lists ? What
is your expected content for Resistance ?
You don't really need to be fluent in C++, the program contains only a few function calls which you can find in the pywin32 API, especially here.
I won't do it for you because the intricacies of windows are not particularly my cup of tea (I'm a linux geek).
Also notice that the author claims that his code works for W2K XP W2K3 Vista, but he does not speak about windows 7 or 8 ...
If n
is an integer, n << 8
is equivalent to n * (2**8)
. The <<
operator is called the left shift operator. It comes from the binary representation of integers, for example 6 is represented as 110
in binary form, and 6 << 3
as 110000
. Other languages use the same convention (in particular the C language, the mother of so many languages).
In python there is no theoretical limit to the size of integers, so that you can write 6 << 1000
and still obtain 6 * 2 ** 1000
. This wouldn't work in languages where integers are limited to 32 bits or 64 bits.
Another feature of python is that the binary operator <<
can be overloaded and have an arbitrary different meaning for user defined data types.
I think this is not possible in csv. Csv does not contain any cell style information. I was able to produce an open-document spreadsheet using the development version of lpod-python (the function to merge cells was added 1 month ago). Here is the code
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals, print_function, division
import os
from lpod.document import odf_new_document
from lpod.table import odf_create_table
from lpod.style import odf_create_style
if __name__=="__main__":
data = [
["Section\n", "Total nb of Points\n", "Line\n", None, "Polygon\n", None],
[None, "Value", "Total length", "Value", "Total length", "Value"],
[None, 15, 1256.5, 20, 125.3, 50],
]
cellstylenum = odf_create_style('table-cell', name='cellstylenum')
cellstylenum.set_properties(area='paragraph', align='start')
cellcenterred = odf_create_style('table-cell', name='cellcenterred')
cellcenterred.set_properties(area = 'text', color="#FF0000")
cellcenterred.set_properties(area='paragraph', align='center')
celltopred = odf_create_style('table-cell', name='celltopred')
celltopred.set_properties(area = 'text', color="#FF0000")
celltopred.set_properties(area='paragraph', align='center')
col3cm = odf_create_style('table-column', width='3cm')
col4cm = odf_create_style('table-column', width='4cm')
row1cm = odf_create_style('table-row', height='1cm')
document = odf_new_document('spreadsheet')
document.insert_style(col3cm, automatic=True)
document.insert_style(col4cm, automatic=True)
document.insert_style(row1cm, automatic=True)
document.insert_style(cellstylenum, automatic=True)
document.insert_style(cellcenterred, automatic=True)
document.insert_style(celltopred, automatic=True)
body = document.get_body()
table = odf_create_table(u"First Table", width = len(data[0]), height = len(data))
body.append(table)
for r in range(len(data)):
for c in range(len(data[r])):
if data[r][c] is None:
continue
z = table.get_cell((c, r))
z.set_value(data[r][c])
if r == 0 and c >= 2:
z.set_style(celltopred)
elif r == 1 and c >= 2:
z.set_style(cellcenterred)
elif r >= 2:
z.set_style(cellstylenum)
table.set_cell((c, r), z)
table.set_span((2,0,3,0))
table.set_span((4,0,5,0))
for column in table.get_columns():
column.set_style(col4cm if column.x == 1 else col3cm)
table.set_column(column.x, column)
pass
row = table.get_row(0)
row.set_style(row1cm)
table.set_row(row.y, row)
#print("table size:", table.get_size())
table.rstrip(aggressive=True)
print(table.to_csv())
test_output_dir = 'test_output'
if not os.path.exists(test_output_dir):
os.mkdir(test_output_dir)
output = …
There are different options
pline = ', '.join([indexfield,] + ps_list)
# or
pline = ', '.join([indexfield,', '.join(ps_list)])
# or
from itertools import chain
pline = ', '.join(chain((indexfield,), ps_list))
The solution is to use lists
loc = locals()
pf_list = [loc["p%sf" % x] + float(loc["p%s" % x]) for x in "abcdefgh"]
ps_list = ["%.2f" % val for val in pf_list]
or dicts
loc = locals()
pf_dict= dict((x, loc["p%sf" % x] + float(loc["p%s" % x])) for x in "abcdefgh")
ps_dict = dict((k, "%.2f" % v) for (k, v) in pf_dict.items()]
print(ps_dict["a"], ps_dict["b"])
The pickle documentation says
The pickle serialization format is guaranteed to be backwards compatible across Python releases.
I think it means that today's python can read yesterday's pickles (see here) but not the contrary.
However, I really think you should check data integrity first. The other thing you can do is dump with the ASCII protocol 0 to see if it changes anything.
pickle.loads()
works very well unless the pickle was written with a different version of python. What you can do is check the integrity of your data by sending the data together with an md5 or sha sum (see module hashlib
). Your remote process must compute the checksum of the pickled data that it writes to output, and your program must compute the checksum of the received data before calling pickle.loads()
. This should tell us if the error comes from pickle.loads()
or not. The standard library functions are heavily tested, so the number 1 suspect is your own program.
These objects are only created once and stored in the views list, but their repaint_canvas()
method is called every time we switch the views. You could change this and always create new objects if you want, but you'd need a good reason to do so. These objects only hold a pointer to the application's canvas, there is no memory leak to worry about.
Here is a code that works for me
from Tkinter import *
class App(object):
def __init__(self, width=256, height=256):
self.width = width
self.height = height
self.root = Tk()
self.root.title("tkinter_test01")
self.root.geometry("%sx%s"%(self.width, self.height))
self.canvas = Canvas(self.root, width=self.width, height=self.height)
self.canvas.pack()
self.views = [win1(self.canvas), win2(self.canvas)]
self.view_idx = 0
self.canvas.bind("<Button-1>", self.switch_view)
self.current_view.repaint_canvas()
def switch_view(self, event):
self.view_idx = (self.view_idx + 1) % len(self.views)
self.current_view.repaint_canvas()
@property
def current_view(self):
return self.views[self.view_idx]
class View(object):
def __init__(self, canvas):
self.canvas = canvas
class win1(View):
def repaint_canvas(self):
self.canvas.delete(ALL)
self.canvas.create_line(10,10,100,100)
class win2(View):
def repaint_canvas(self):
self.canvas.delete(ALL)
self.canvas.create_line(30,30,100,40)
app = App()
app.root.mainloop()
Take a page containing a list of sentences, like this one (take only the first 5 sentences). Then with a calculator, compute the average number of words per sentence by hand and note carefully everything you do. This should give you a working algorithm. Write pseudo code, then python code.
You can use a namedtuple as a simple container
from collections import namedtuple
FileInfo = namedtuple("FileInfo", "path foo bar baz")
mylist=[]
for file in glob.glob(inputpath+"\\*.txt"):
mylist.append(FileInfo(file, value1, value2, value3))
import pickle
pkl = "fileinfo.pkl"
with open(pkl, "wb") as ofh:
pickle.dump(mylist, ofh)
with open(pkl, "rb") as ifh:
print(pickle.load(ifh))
You can also try to read the file by chunks
import io
MB = 1 << 20
# read the file by chunks of 64 megabytes
with io.open('input.txt', mode="r+b", buffering = 64 * MB) as infile:
# etc
i made two python files and both python files will gives some output and i want to print that output at the same time by using third python file by the help of multithreading, how could i do that,
I found your question interesting, so I wrote a small class to do this, see if it can help you
#!/usr/bin/env python
# -*-coding: utf8-*-
# file printerthread.py
from __future__ import unicode_literals, print_function
import Queue
import sys
import threading
class PrintingThread(threading.Thread):
def __init__(self, file = sys.stdout):
threading.Thread.__init__(self)
self.queue = Queue.Queue()
self.cond = threading.Condition()
self._shutdown = 0
self.file = file
def run(self):
with self.cond:
while True:
self.cond.wait()
if self._shutdown == 2:
self._abort()
return
else:
self._print_queue()
if self._shutdown:
return
def shutdown(self, value = 1):
assert value in (1, 2)
with self.cond:
self._shutdown = value
self.cond.notify()
self.join()
def _abort(self):
try:
while True:
self.queue.get_nowait()
self.queue.task_done()
except Queue.Empty:
return
def _print_queue(self):
try:
while True:
data = self.queue.get_nowait()
self.file.write(data)
self.queue.task_done()
except Queue.Empty:
return
def print(self, *args, **kwd):
sep = kwd.get('sep', ' ')
end = kwd.get('end', '\n')
s = sep.join(str(x) for x in args) + end
self.write(s)
def write(self, s):
if len(s) == 0:
return
with self.cond:
self.queue.put(s)
self.cond.notify()
Here is a possible main program
#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import unicode_literals, print_function
from printerthread import PrintingThread
import time
def main():
t = PrintingThread()
t.start()
for i in range(5):
time.sleep(1)
for j in range(3):
t.print(time.time())
t.shutdown()
if __name__ == "__main__":
main()
#=======================================================
""" my output -->
1354444871.71
1354444871.71
1354444871.71
1354444872.71
1354444872.71 …
In your code, num
is a string, and numin
is an integer. It means that the arithmetic expressions involving num
won't work as expected. The best thing to do is to replace line 2 with num = int(num)
and forget about numin
. You can even write num = int(num) % 100
.
To answer your initial question, you can write print "%dst" % 121
, or print "{0}st".format(121)
or print str(121) + "st"
. My preferred way is the format method.
The last elif...
in your code could also be replaced by a single else:
. It seems to me that if (num % 10 == 1) and (num != 11)
would be easier for the reader that num > 20
, etc. You could also have a variable r = num % 10
and write if (r == 1) and (num != 11)
etc.
Finally, here is an advanced solution
num = int(num) % 100
suffix = dict(enumerate(("st", "nd", "rd"), 1))
s = "th" if num in (11, 12, 13) else suffix.get(num % 10, "th")
print "{0}{1}".format(num, s)
If you don't want to generate the page dynamically, you can generate it once a week and store an html file when you run your script. You could use a template engine like Mako for variable substitution in the html file. It is very easy to do.
Hint: if there is a vertex at a point (x0, y0)
, the other vertices are at points
x, y = (x0+ a * i + b * j, y0 + c * j)
where a, b, c
are 3 given numbers and i, j
are varying integers.
People stuck with XP because it was lean and clean, and didn't want to change to Vista because it was slow and clumsy? Is that the kind of issue between Python 2x and Python 3x?
No it's not exactly that kind of issue. Python 3 is actually cleaner than python 2. Only many libraries were written for python 2 and people are slow porting them to python 3.
You can have more than one install of python on your computer. If your editor needs python 2 to run, you can still write python 3 code with it !
Here is how to display the base64 image using tkinter and PIL in python 2
if __name__ == "__main__":
from StringIO import StringIO
import Tkinter
from PIL import ImageTk, Image
root = Tkinter.Tk()
#root.bind("<Button>", lambda event: event.widget.quit())
root.geometry('+%d+%d' % (100,100))
f = StringIO(base64.decodestring(str(rainbow_jpg_b64)))
image = Image.open(f)
zoom = 5
image = image.resize((zoom*image.size[0], zoom*image.size[1]))
root.geometry('%dx%d' % (image.size[0], image.size[1]))
tkpi = ImageTk.PhotoImage(image)
label_image = Tkinter.Label(root, image=tkpi)
label_image.place(x=0,y=0,width=image.size[0],height=image.size[1])
root.title("rainbow")
root.mainloop()
Nice rainbow!
You can tell where the function was called from using module inspect
#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import unicode_literals, print_function
__doc__ = """ sandbox.funccall -
show how to print where a function was called from
"""
import inspect
import os
def calling_line(level):
level = max(int(level), 0)
frame = inspect.currentframe().f_back
try:
for i in xrange(level):
frame = frame.f_back
lineno, filename = frame.f_lineno, frame.f_code.co_filename
finally:
del frame
return lineno, filename
def thefunc(*args):
lineno, filename = calling_line(1)
print("thefunc() was called from {0} at line {1}".format(
os.path.basename(filename), lineno))
return 3.14
def foo():
x = thefunc() ** 2
if __name__ == "__main__":
foo()
""" my output -->
thefunc() was called from funccall.py at line 32
"""
Otherwise, yes, nametest.__name__ = ...
resets the original variable. __name__
is an ordinary global variable which is automatically inserted in the module's namespace. Another interesting variable which exists only for imported modules is__file__
.
It's a very good remark, in python 3, the bytes type is already a sequence of integers
>>> s = bytes("hello", encoding="utf8")
>>> s
b'hello'
>>> s[0]
104
>>> s[1]
101
>>> list(s)
[104, 101, 108, 108, 111]
In python 2, there is also an array type
>>> import array
>>> x = array.array("B", "hello")
>>> list(x)
[104, 101, 108, 108, 111]
>>> x
array('B', [104, 101, 108, 108, 111])
This python 2.7 snippet adds a thin layer of sugar on the itertools module's api, allowing many of its functions to be used as decorators and adding some new functions. Enjoy !