absolute and relative paths.
Rember to use \\ or /(windows)
\ count as a new line.
So as an example.
c:/tmp/163282.xml
or
c:\\tmp\\163282.xml
absolute and relative paths.
Rember to use \\ or /(windows)
\ count as a new line.
So as an example.
c:/tmp/163282.xml
or
c:\\tmp\\163282.xml
For help you have to post your code,we can not guess how your code are set up.
Just wonder what you want to do.
If you just want to ping,this is an easy solution.
import os
os.system("ping " + '192.168.2.1')
#Extern adress
import os
os.system("ping " + 'www.goolge.com')
Krstevski read this again.
and several other trivial programs in Python 3.1,
Raw_input has been removed in python 3.x(input in python 3.x dos the same as raw_input in python 2.x)
So Purnima12 use input with Krstevski soultion.
For dates there is a build datetime module to look at.
http://www.daniweb.com/code/snippet216493.html
http://www.daniweb.com/code/snippet216475.html
A general rule is that use regular expression on html is not god at all.
If you want to read why is a bad idèe.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags
BeautifulSoup and lxml are god tool for this.
To get bettter help give us a sample off the html.
And be very correct what you want to get out html.
In some other languages the content of the file (1000) would be a numeric value, not a string. Thanks
In many other lanuages you need to declare vaiables.
In python there is no need for this,but off course datatypes is always there.
C++
int age;
age = 30
Python
age = 30
Test in IDLE.
>>> age = 30
>>> type(age)
<type 'int'>
>>>
So do this if you not sure of datatype.
>>> f = open('C:/saldo.txt')
>>> saldo = f.readline()
>>> saldo
'100'
>>> print saldo
100
>>> type(saldo)
<type 'str'>
>>> if saldo > 1000:
print True
else:
print False
True
#As you see this is worng
#Because saldo is a string
>>> if int(saldo) > 1000:
print True
else:
print False
False
How dos your money.txt look?
Change to this money = int(money) - Bet
.
Type check print type(money)
. print type(Bet)
Your desgin could be better, a long funtion that only ends(no loop)
Try to make a main function that has meny and question then that function call the bet function.
Betting is done and it goes back to main.
Use this f = open('C:/teste.txt', 'w')
.
Or this f = open('C:\\teste.txt', 'w')
. \
count as newline \\
== Backslash (\)
In windows i always use this c:/
.
http://docs.python.org/reference/lexical_analysis.html#string-literals
import BeautifulSoup as bs
html = """\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Test JSON </TITLE>
<script language="JavaScript">
function checkJSON()
{
try
{
var v = eval(TextJSON.value);
var OK='OK'
document.write("OK");
}
catch (ex)
{
document.write("Error:"+ex);
}
TextJSON.focus();
}
</script>
</HEAD>
<BODY >
<table width="100%" border="0">
<tr>
<td>
<textarea rows="15" cols="70" id="TextJSON" Style = "visibility:hidden">Hello</textarea>
</td>
</tr>
</table><script language="JavaScript">
checkJSON();
</script>
</BODY>
</HTML>
"""
soup = bs.BeautifulSoup(html)
divs = soup.findAll('textarea')
children = divs[0].contents
print divs[0].string # Hello
This find Hello in test12js.txt
Html dos not ever output anything as Gribouillis pointed out.
You parse html an find text like i did here.
You are better off learing more basic stuff about python and html.
Why most of can use free with tool like Inno setup
And for exe Gui2exe make it easy
I also use UPX to compress dll,exe,pyd.
Look at this post for learning PyQt,i like wxpython better as many her on daniweb.
http://www.daniweb.com/forums/thread191210.html
There are license problem with PyQt.
How can I add the vcontents in a tabbed view?
You can use Qtabwidget.
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtabwidget.html
import os, sys
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setGeometry(0,0, 200,300)
self.setWindowTitle("my window")
self.resize(200,300)
self.setMinimumSize(200,300)
self.center()
tab_widget = QtGui.QTabWidget()
tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
p1_vertical = QtGui.QVBoxLayout(tab1)
p2_vertical = QtGui.QVBoxLayout(tab2)
tab_widget.addTab(tab1, "Main")
tab_widget.addTab(tab2, "Description")
vbox = QtGui.QVBoxLayout()
vbox.addWidget(tab_widget)
self.setLayout(vbox)
def center(self):
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
app = QtGui.QApplication(sys.argv)
frame = MainWindow()
frame.show()
sys.exit(app.exec_())
Dirdialog may be what you are looking for.
import wx
class MyFrame(wx.Frame):
'''Info abot class | Doc string'''
def __init__(self, parent, mytitle, mysize):
wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
self.SetBackgroundColour('light blue')
self.panel = wx.Panel(self)
b = wx.Button(self.panel,-1,"Create and Show a DirDialog", (50,50))
self.Bind(wx.EVT_BUTTON, self.OnButton, b)
def OnButton(self, evt):
dlg = wx.DirDialog(self, "Choose a directory:",
style=wx.DD_DEFAULT_STYLE
#| wx.DD_DIR_MUST_EXIST
#| wx.DD_CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
self.log.WriteText('You selected: %s\n' % dlg.GetPath())
dlg.Destroy()
if __name__ == "__main__":
app = wx.App()
mytitle = 'My window'
width = 300
height = 200
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
You shold look better there are many post about this.
here is one just postet.
http://www.daniweb.com/forums/thread256661.html
There are very good reason why board like this should have registration and log in.
Board want serious user and not alot off spam.
Enough off that and back to your question.
Wxpython is great for more advance GUI look.
Look at this post.
http://www.daniweb.com/forums/thread252780.html
Wxpython has a demo where you can look at it live.
PyQt is also an good and advance gui toolkit.
VLC media player use QT as GUI.
I did more reading into the setup problem. Seems I need to include a dll that isn't pulled automatically from Python2.6 and above
From command line.
C:\>python -m timeit "for i in xrange(100): pass"
1000000 loops, best of 3: 1.77 usec per loop
#Are tuple faster than list?
C:\>python -m timeit (1,2,3,4)
10000000 loops, best of 3: 0.0226 usec per loop
C:\>python -m timeit [1,2,3,4]
10000000 loops, best of 3: 0.194 usec per loop
#Yes tuple are faster than list
You have to explain better.
Give an correct example how it shoul look(input and output)
Eksp.
This lines in sample--a, i will have in sample--b.
Sample--b is a new file or sample--b is in same file.
Sample--A
CHIP FRAME_4X,
$ (1, 4HTFRR2-0A-00, AD=0.005, SF=0.5)
ROWS 38500/76200
Output.
Sample--B
CHIP FRAME_4X,
$ (1, 4HTFRR2-0A-00, AD=0.005, SF=1) #--- SF change to FRAME_5X
$ (2, 4HTFRR3-0A-00, AD=0.005, SF=1)
$ (3, 4HTFRR6-0A-00, AD=0.005, SF=1) #---SF change to FRAME_5X
ROWS 15200/83400 #----ROWS change to FRAME_5X
*!
CHIP M1_4X,
$ (1, 4HTM1R2-0A-00, AD=0.005, SF=1) #---SF change to M1_5X
$ (2, 4HTM1R3-0A-00, AD=0.005, SF=1)
$ (3, 4HTM1R6-0A-00, AD=0.005, SF=1) #---SF change to M1_5X
ROWS 5200/3400 #----ROWS change to CHIP_5X
CHIP FRAME_4X,
$ (1, 4HTFRR2-0A-00, AD=0.005, SF=0.5)
ROWS 38500/76200
Somthing like this where we don have to guess how you want it.
In first post.
After you got the basics of Python under your belt, the best way to get a good knowledge of the language and improve your coding skills is to start on a project you are interested in.
That means that you have to know python good.
You can still be a beginner after 1-3 year it depends how much time you put in to learning programming.
Python is on the most easy language to learn,but it take time to be a good programmer where you can solve problem on your own(without hours on google for the most basic thing)
To day people are in a hurry to learn,this is a good read.
Teach Yourself Programming in Ten Years
Read this.
http://www.daniweb.com/forums/announcement114-2.html
I didn't understand on what you trying to say, but I'm leaving this problem for "professionals people"
Yes leave your homework to "professionals people".
Do you see how stupid that look?
Use 4 space for indentations(and nothing else ever)
What is you data input?
Not sure what you are trying do do.
Here something you can look at.
>>> import sys
>>> help(sys.getsizeof)
Help on built-in function getsizeof in module sys:
getsizeof(...)
getsizeof(object, default) -> int
Return the size of object in bytes.
>>> a = 5
>>> sys.getsizeof(a)
12
>>> a = ['hi', 'test', '55']
>>> sys.getsizeof(a)
48
>>>
import sys
data = 55
if sys.getsizeof(data) < 512:
print 'Data is %s bytes and less than 512 bytes' % (sys.getsizeof(data))
else:
print 'Data is %s more than 512 bytes' % (sys.getsizeof(data))
'''Out-->
Data is 12 bytes and less than 512 bytes
'''
>>> import time
>>> dir(time)
['__doc__',
'__name__',
'__package__',
'accept2dyear',
'altzone',
'asctime',
'clock',
'ctime',
'daylight',
'gmtime',
'localtime',
'mktime',
'sleep',
'strftime',
'strptime',
'struct_time',
'time',
'timezone',
'tzname']
>>> help(time.sleep)
Help on built-in function sleep in module time:
sleep(...)
sleep(seconds)
Delay execution for a given number of seconds. The argument may be
a floating point number for subsecond precision.
>>>
http://code.google.com/p/gui2exe/
Start with python <your path> GUI2Exe.py
choose your wxpython script.
Set Optimize 2 | Compressed 3 | Bundle Files 3
Complie-->finish test your program.
So first you do something like this.
html = '''\
<HEADLINE text="This is headline 1">
<PARAGRAPH file="path to the file.txt">'''
l = []
for item in html.split('\n'):
if item.startswith('<HEADLINE'):
l.append(item.split('"')[1])
ll = ''.join(l)
print ll
'''Out-->
This is headline 1
'''
And then you want that text to go in a new html code?
Eksp. <p>This is headline 1p>
.
To take out elements from webpages look at.
BeautifulSoup and lxml
This question is very unclear.
Python code and html is text and png is an image format.
So you can not convert this code to and image format off course.
Are you trying to make a fake png file with html and python code?
See if this help make your code shoter and clearer.
Ask if somethis is unclear.
l = []
for i in open('dna.txt'):
if i.split()[1] == '1':
l.append(i.strip().rstrip('1'))
print l
'''Out
['AAAAAGATAAGCTAATTAAGCTACTGGGTT ', 'AAAAAGGGGGCTCACAGGGGAGGGGTAT ']
'''
>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
>>> #Use method date and timedelta
>>> print datetime.date.today()
2010-01-11
>>>
>>> #Find now days since 1 Jan 1901
>>> one_day = datetime.timedelta(days=1)
>>> long_time_ago = datetime.date(1901, 1, 01)
>>> print to_day - long_time_ago
39822 days, 0:00:00
Look like you use python 3
>>> #Python3 has only input that return a string
>>> user_input = input('Give me a number: ')
Give me a number: 10
>>> user_input
'10'
>>> type(user_input)
<class 'str'>
>>> print 'Your number was %s' % (user_input)
SyntaxError: invalid syntax (<pyshell#4>, line 1)
>>> print ('Your number was %s' % (user_input))
Your number was 10
>>> #And print has become function print()
>>>
Not possible to help you if you dont post the code.
Look at this.
http://wxpython.webs.com/tutorial5.htm
Install wxpython demo.
I have made put files in folder named c:\demo.
To start python c:\demo\demo\demo.py
For loop will only iterate one time over the list and not find duplicated words.
You can use text.find() method in a while loop.
This will iterate over all word in the text, when all search word are found text.find() will return -1.
Example.
text = """\
Hi,i have a nice car.
I drive to work every day in my car.
This text will find my car,....car.
"""
search_word = "car"
found = text.find(search_word)
while found > -1:
print search_word, "found at index", found
found = text.find(search_word, found + 1)
'''Out-->
car found at index 17
car found at index 54
car found at index 82
car found at index 90
'''
i dnt knw if my code is even right.. plz help
No is far from right,this you should know if you try to run it.
Look at this one more time,to you think this will run?
if:
finish=no
print " student(s) got 0 marks
student(s) got 1 marks
student(s) got 2 marks
student(s) got 3 marks
student(s) got 4 marks
student(s) got 5 marks"
And this with singel quote will no work """ my multiline text """
.
Just to show one way to count.
def mark():
m1,m2 = 0,0
for i in range(5): #just for test ask 5 times,you can use a while loop and breake out if no
marks = raw_input("please enter the marks: ")
if marks == '1':
m1 += 1 #a counting method
elif marks == '2':
m2 += 1
print '%s student got:1' % (m1)
print '%s student got:2' % (m2)
mark()
'''Out-->
please enter the marks: 1
please enter the marks: 1
please enter the marks: 1
please enter the marks: 2
please enter the marks: 2
3 student got:1
2 student got:2
'''
If there are many user that will enter data you have to return data out off this(your funtction) to save student marks count.
No if you run mark() several times it will off course reset student count every time.
If this is a school assignment is better that you copy in the correct text for assignment so we dont have to guess.
…
Link are not working but look the where working on a skinning system with xml.
http://wiki.wxpython.org/TG.Skinning
Media player use a xml skinning system i think.
Did find it here,but dont look like much have happend i last 4 years.
http://techgame.net/projects/Framework/wiki/SkinningFramework
We could make this a post where we share idèe how to get wxpython to look fancy and modern.
I think we are many that like wxpython and want it to look good.
Here are a link for a fancy window.
http://hasenj.wordpress.com/2009/04/14/making-a-fancy-window-in-wxpython/
Mores style tips are welcome.......
Create panel with Image as background and then Load wxBitmaps and coloured wxStaticTexts and et al
Is this technique practical and possible?
It should be possible i think.
Here is my alarmclock made for fun,where i testet out diffrent style with wxpython.
Use transparent png images ang png image buttons.
There are several problem with your code.
Function within a function you dont use it in code like this as vegaseat poinet out.
You break
out to nothing.
This line will not work print "Wrong Input , x"
in exception handling because off x
I rewrite to show a better direction to go.
This way it print result,and then main menu come again.
def mm():
while True:
try:
x = float(raw_input("Enter lenght in cm: "))
mm = x * 10
print '%s is %.3fmm\n' % (x,mm)
break
except ValueError:
print "Wrong Input,try again"
def cm():
while True:
try:
x = float(raw_input("Enter lenght in mm: "))
cm = x / 10
print '%s is %.3fcm\n' % (x,cm)
break
except ValueError:
print "Wrong Input,try again"
def main():
while True:
print 'Welcome to my menu\n'
print '(1) Convert cm -> mm'
print '(2) Convert mm -> cm'
print '(q) Quit'
choice = raw_input('Enter your choice: ')
if choice == '1':
mm()
elif choice == '2':
cm()
elif choice == 'q':
exit()
else:
print 'Not a correct choice:', choice
if __name__ == '__main__':
main()
>>> Input = '55'
>>> type(Input)
<type 'str'>
>>> n = int(Input)
>>> n
55
>>> type(n)
<type 'int'>
Dictionary has keys() and values()
You dont show all code.
Example.
>>> tanks = {'tiger': 'a55', 'trunk': 'f77'}
>>> for tank in tanks.values():
print tank
a55
f77
>>> for tank in tanks.keys():
print tank
tiger
trunk
#--------
>>> dir(tanks) #this show methods under dictionary
Dos it give you any error message?
They code is working fine here.
Test with this ico,to see if your ico file is the problem.
http://www.iconspedia.com/icon/snowman.html
Klikk on Download.ico.file
Can put in exception handling,it will give an TclError if ico-file not found.
from Tkinter import *
root = Tk()
root.minsize(290, 200)
root.title("My Window")
try:
root.wm_iconbitmap('s.ico')
root.mainloop()
except TclError:
print 'No ico file found'
Not the best example of list comprehension.
Vegaseat pointet out the problem.
More basic off list comprehension.
>>> l = [0 for i in range(10)]
>>> #So what will l print?
>>> l
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> #So to understand this we can write it like this
>>> l = []
>>> for i in range(10):
l.append(0)
>>> l
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> l = []
>>> for i in range(10):
l.append(i)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> #So how to do this with list comprehension?
>>> l = [i+0 for i in range(10)]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> #So to think off it like this
>>> #l = [expr for-clause if-clause]
>>> #We try with if-clause to get only even numbers
>>> l = [i+0 for i in range(10) if i%2 == 0]
>>> l
[0, 2, 4, 6, 8]
>>> #If we write this without list comprehension
>>> l = []
>>> for i in range(10):
if i%2 == 0:
l.append(i)
>>> l
[0, 2, 4, 6, 8]
>>>
#The basic
#list comprehension.
l = [expr for-clause if-clause]
#Without list comprehension.
l = []
for variable in sequence :
if filter:
r.append( expr )
The autorun.inf file has to be on your usb/cd/dvd drive.
Or nothing will start.
Your exe file you can have on your pc.
Just set path in your autorun.inf
Eksp.
open = c:/my_backup/backup.exe
If you make a script that do what you want, and then use py2exe.
It should be possible to to it like this.
[autorun]
open = Your_py2exe_file.exe
action = Run my program
icon = your.ico
Save as autorun.inf
in your root usb drive.
You also have tool like PStart that you can use.
http://www.pegtop.de/start/
Use code tag now we can not see if your indentation is correct.
You dont have strip()
in your script.
>>> a = 'test \n'
>>> len(a)
11
>>> #Without whitespace and new line
>>> b = a.strip()
>>> b
'test'
>>> len(b)
4
>>>
So you read in file(for loop) strip()
it and use len()
to find word that has more than 20 characters.
fin = open('c:/python26/words.txt')
for line in fin:
word = line.strip()
if len(word) > 20:
print word
'''--> Output
counterdemonstrations
hyperaggressivenesses
microminiaturizations
'''
You can do that with most gui toolkit.
Wxpython is the most populare on this forum.
Look at sticky at top for example off gui toolkit for python.
http://zetcode.com/wxpython/menustoolbars/
A coulpe of class that show __str__ and __repr__ methods.
import datetime
class Time(object):
def __init__(self,date):
self.date = date
def __str__(self):
"""Return a pleasant representation."""
return 'Return a human-readable string: %s' % (self.date)
t = Time(datetime.date.today())
print t #The __str__ method of a class is called whenever Python needs a string representation of an object
'''
Return a human-readable string: 2009-12-27
'''
class Time(object):
def __init__(self,date):
self.date = date
def __repr__(self):
'''We use __repr__ to produce a clear definition of how to recreate the given object'''
return 'Return an expression: %r' % (self.date)
t = Time(datetime.date.today())
print t
'''
Return an expression: datetime.date(2009, 12, 27)
'''
Navigate and getting help
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
>>> dir(datetime.date)
['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']
>>> dir(datetime.date.today)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> #There are no more methods only special method that get called when you use the class
>>> #we look at __doc__
>>> print datetime.date.today.__doc__
Current date or datetime: same as self.__class__.fromtimestamp(time.time()).
>>> #Or you can use help
>>> help(datetime.date.today)
Help on built-in function today:
today(...)
Current date or datetime: same …
Dont use ;
in python.
output = "The number is: "
num = 12
print '%s%d' % (output,num)
'''
The number is: 12
'''
output = "The number is: "
num = 12
output+=num
print output
Error message is pretty clear. TypeError: cannot concatenate 'str' and 'int' objects
>>> output = "The number is: "
>>> type(output)
<type 'str'>
>>> num = 12
>>> type(12)
<type 'int'>
>>> #As you see we have a string and integer
>>> output + num
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
output + num
TypeError: cannot concatenate 'str' and 'int' objects
>>> str(num) #convert to string
'12'
>>> output + str(num)
'The number is: 12'
>>>
You have to understand the basic of wxpython.
Then you use only the part of code that you need.
Examlpe.
import wx
class MyFrame(wx.Frame):
'''info abot class | Doc string'''
def __init__(self, parent, mytitle, mysize):
wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
#---| Window color |---#
self.SetBackgroundColour('light blue')
#---| Panel for frame |---#
self.panel = wx.Panel(self)
if __name__ == "__main__":
app = wx.App()
mytitle = 'My window'
width = 300
height = 200
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
Now i have a basic window.
So start wxpython demo.
I what to use choicebox code from demo.
Now i only copy the part i need,not all demo code.
import wx
class MyFrame(wx.Frame):
'''info abot class | Doc string'''
def __init__(self, parent, mytitle, mysize):
wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
#---| Window color |---#
self.SetBackgroundColour('light blue')
#---| Panel for frame |---#
self.panel = wx.Panel(self)
#Demo code
sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight']
#Demo code
self.ch = wx.Choice(self.panel, -1, (100, 50), choices = sampleList)
self.Bind(wx.EVT_CHOICE, self.EvtChoice, self.ch)
#Demo code
def EvtChoice(self, event):
a = event.GetString() #I change event handling like this i dont wanne write out like in the demo
self.a = wx.StaticText(self.panel, -1, str(a), pos = (105,80))
if __name__ == "__main__":
app = wx.App()
mytitle = 'My window'
width = 300
height = 200
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
It`s better that you make a simple class and post that code.
Then ask what you dont understand.
If you dont now how to make a class at all,read some tutorials or seek google.