temp = p.load('systemaccess.txt')
temp = p.load('systemaccess.txt')
I think what you're trying to do is:
for item in metlist:
data1[2].append(item)To see what you did won't work, try typing data1[2]. It gives you ..thus there is only one element, and nothing at position 1.
While I agree with you that he should be using append instead of insert, I don't believe that his error is being caused by there only being one element:
>>> d = ['a']
>>> d.insert(1,'b')
>>> d
['a', 'b']
you could just as easily do s = 'c:\\test.doc'
you could also do a hard sleep:
import time
time.sleep(1) # 1 second delay in processing
An even easier workaround for being able to import modules from ANY directory is to modify the sys.path variable at run time. So at the beginning of your code do something like this:
import os,sys
sys.path.append('/path/to_my/module')
import my_custom_module
And if you're working with a hard-coded windows path make sure you escape your escape characters (ie, C:\\Documents and Settings\\Administrator\\My Documents )
A better way to handle paths is using os.path.join()
>>> import os
>>> os.path.join('C:\\', 'Documents and Settings', 'Administrator', 'My Documents')
'C:\\Documents and Settings\\Administrator\\My Documents'
>>>
Perhaps this thread will answer your question
Oh and P.S.; command = "OK" + os.linesep
is a platform independent way to implement that...
What didn't work about str(row)? What kind of error did you get? The only thing I can think of is that you didn't add any line endings?
>>> import os
>>> os.linesep
'\r\n'
This depends on the type of system you're on. \r\n
is Windows, \n
is Linux, and I believe that \r
is Mac (although I've never used one so I don't really know).
I don't know if there's a specific function to do it, but you could do a simple for loop like:
>>> l = 'hi;your,face.is;on,fire'
>>> for c in [';',',','.']:
... l = l.replace( c, '_' )
...
>>> l
'hi_your_face_is_on_fire'
>>>
Or roll your own little function ie,
>>> l = 'hi;your,face.is;on,fire'
>>> def replaces( inp, old, new ):
... for c in old: inp = inp.replace( c, new )
... return inp
...
>>> l = replaces(l, ';,.', '_')
>>> l
'hi_your_face_is_on_fire'
>>>
Same function, using list instead of string of chars
>>> l = 'hi;your,face.is;on,fire'
>>> l = replaces(l, [ ';', ',', '.' ], '_')
>>> l
'hi_your_face_is_on_fire'
>>>
This is from the RichTextCtrl demo in the wx Docs and Demos package.
self.rtc = rt.RichTextCtrl(self, style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER);
wx.CallAfter(self.rtc.SetFocus)
self.rtc.Freeze()
self.rtc.BeginSuppressUndo()
self.rtc.BeginParagraphSpacing(0, 20)
self.rtc.BeginAlignment(rt.TEXT_ALIGNMENT_CENTRE)
self.rtc.BeginBold()
self.rtc.BeginFontSize(14)
self.rtc.WriteText("Welcome to wxRichTextCtrl, a wxWidgets control for editing and presenting styled text and images")
self.rtc.EndFontSize()
self.rtc.Newline()
self.rtc.BeginItalic()
self.rtc.WriteText("by Julian Smart")
self.rtc.EndItalic()
self.rtc.EndBold()
self.rtc.Newline()
The code is too large to post here, but if you just look into RichTextCtrl you'll find your answers.
Here's the code for the and other formatting options on the toolbar/menubar:
def OnBold(self, evt):
self.rtc.ApplyBoldToSelection()
def OnItalic(self, evt):
self.rtc.ApplyItalicToSelection()
def OnUnderline(self, evt):
self.rtc.ApplyUnderlineToSelection()
def OnAlignLeft(self, evt):
self.rtc.ApplyAlignmentToSelection(rt.TEXT_ALIGNMENT_LEFT)
def OnAlignRight(self, evt):
self.rtc.ApplyAlignmentToSelection(rt.TEXT_ALIGNMENT_RIGHT)
def OnAlignCenter(self, evt):
self.rtc.ApplyAlignmentToSelection(rt.TEXT_ALIGNMENT_CENTRE)
Description from the vpython homepage:
VPython is a package that includes:
- the Python programming language
- the IDLE interactive development environment
- "Visual", a Python module that offers real-time 3D output, and is easily usable by novice programmers
- "Numeric", a Python module for fast processing of arrays
VPython is free and open-source.
def line_sum_and_count(line):
"""Finds the sum and count of the numbers in the given line of text."""
#-----------------------------------------------------
data = line.split()
tally = 0
for i in data:
tally += float( i )
#-------------------------------------------------------
return tally, len( data )
Here's a different way to tackle the first function. I think your problem was the whole [n] + [n+1] thing... So that would mean
Iteration 1: 14 + 20
Iteration 2: 20 + 17
Iteration 3: 17 + Out of Bounds
so not only were you accumulating incorrectly, but you weren't doing anything like sum += x (sum = sum + x ). Do you understand what I mean? An accumulator is best done as the above code, you initialize your accumulator first to 0 (tally), then on each iteration you would just do tally += x (tally = tally + x). I hope that makes sense.
Secondly, it's easier if you just iterate over the list that is created by split(), and use the float conversion dynamically instead of iterating once to convert all the elements to floats, and then a second iteration for the "summing".
Thirdly, I agree that you should avoid using built in functions as variable names. You should consider switching to a Python editor that has syntax highlighting and/or auto-completion, as this will help to identify function names easily.
Finally, don't use the string module. It clutters your code unnecessarily. Instead of string.split(x, d) you can simply use x.split(d), …
Is anyone else getting a little tired of the "I Googled it and couldn't find anything" lie. "python sum list" brings up "total = sum(list_name)" as the second hit. Searching for "python adding list" gives both the sum() and a for() loop as examples on the fourth hit. But is it a complete waste of time to call them on it? Perhaps we should start posting the Google link. I am more than willing to help anyone with a real programming problem, but this wasting everyone's time can lead to fewer programmers who help because of all of the cruft that one has to wade through.
It is increasingly rare to find anything else on this forum. I left a forum before coming here solely based on this fact. Endless "I couldn't find the answer anywhere else..." and "I have a problem: I'm trying to make a program that '<copy_and_paste from Instructions for homework' and I'm stuck, don't have any code, so how would I go about this? And it's super urgent PLS help"
I wish I could just delete these posts and stop wasting our collective time.
Here's a comparison:
>>> a = [1,2,3,4,5,6]
>>> reduce(lambda y,x: x+y, a)
21
>>> sum = 0
>>> for i in a:
... sum+=i
...
>>> sum
21
>>>
Reduce is a way to perform a function cumulatively on every element of a list. It can perform any function, so if you define your own modulus function, it will repeatedly perform that function on each element of the list. In order to avoid defining an entire function for performing x+y, you can instead use a lambda function; which would benefit you more if you googled it, because I'm terrible at explaining them.
If you open up a python interpreter and type help(reduce), this is what you get:
>>> help(reduce)
Help on built-in function reduce in module __builtin__:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
>>>
HTH
sys.argv is used for passing command line arguments to your program. It is a list, and the first value sys.argv[0]
is always the name of your program.
So let's say you open up a terminal and type in python my_prog.py foo bar
Then sys.argv's contents would be
[0] my_prog.py
[1] foo
[2] bar
So by using slicing and saying sys.argv[1:] the author is getting everything except for the my_prog.py.
HTH
Ghar. For some reason os.system() isn't friendly with commands that have spaces in their paths (even if you enclose them with ""). Best practice is to swtich to a slightly more robust execution module such as subprocess (if you're on 2.4 or greater), or popen
Don't double post... but regardless, check your other post in this same forum.
First you'll need to learn how to use code tags. As your code stands, it is unreadable because all indentation has been lost. If you use code tags, your code is not only readable, but forum members can easily copy and paste it into their code editors to tinker with.
Code tags go like this:
[code=python] # My code goes between these code tags
[/code]
If you ever post in another forum you can replace "python" with any other syntax (php, perl, html, java, etc.)
So on a brief over look of your code I'm confused by string.sum() .. What does that do? I don't have a sum() function for the built-in string module. Is this a custom module? Also, I don't think you should bother importing the string module. name = name.lower()
will do the same thing.
I don't know if there is a module to simply find factors, but it is such a simple operation that you can make your own function... from the psuedo-code I posted eralier:
>>> def get_factors( inp ):
... ret = [ 1, inp ]
... for i in xrange( inp + 1 ):
... for j in xrange( i, 1, -1 ):
... if i * j == inp:
... ret += [ i, j ]
... ret.sort()
... return ret
...
>>> get_factors(6)
[1, 2, 3, 6]
Yes you should figure out the factors portion of your code first... one obvious problem might be that you never change b? So you're always multiplying h*1 ... and secondly, if h*b == n; wouldn't that make h and b both factors of n ??
You can do something like:
inp = user input
for i in (1, inp+1):
for j in (i, 1, -1):
if i*j == inp:
i and j are factors
return factors
>>> reduce(int.__mul__, L) 362880 >>>
Wow, I really like that.. never used reduce.
A suggestion for the OP: so that the above isn't so cryptic maybe it'll be easier to wrap your head around in this form:
>>> L = range(1,10)
>>> reduce(lambda x, y: x*y, L)
362880
>>>
You might want to rethink what the line c = factors [0:] * factors [:40]
is doing...
Look at this example for what happens using * on lists:
>>> [ 1, 2, 3 ] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> [ 1, 2, 3 ] * [ 2, 3 ]
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'list'
Yar. I actually looked at what your code does and it is extremely over complicating the matter... here's a much simpler method:
import string
letters = list(string.letters) + list(string.digits) + ['\n','\r',' ']
letters.sort()
numbers = [ ord(i) for i in letters ]
# Ascii values in the following list
result3=[83,97,109,117,101,108,32,83,109,105,116,104,13,10,13,10,84,\
104,97,110,107,32,121,111,117,32,102,111,114,32,108,111,111,\
107,105,110,103,32,116,104,101,32,111,116,104,101,114,32,119,\
97,121,32,111,110,32,116,104,101,32,105,110,99,114,101,97,115,\
101,100,32,108,101,118,101,108,115,32,111,102,32,116,111,120,\
105,99,32,99,104,101,109,105,99,97,108,115,32,105,110,32,116,104,\
101,32,114,105,118,101,114,32,114,117,110,110,105,110,103,32,97,\
108,111,110,103,115,105]
out_str = ''
for i in result3:
if i in numbers:
idx = numbers.index(i)
out_str += letters[idx]
print out_str
Usually it's as simple as python myscript.py
If python isn't in the path you'd need the full path to the python executable.
also, which version of Python is this? If you are using the latest you should be using the subprocess module as it's much more efficient and easier to use than the old threading module, which is why it's becoming the new standard ;)
Oh!! also for the ascii values use another string comprehension!!!
>>> [ ord( lett ) for lett in string.letters ]
[97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90
PSST! Secret:
>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
And PSST!!! To turn them into lists use list comprehension:
>>> [ lett for lett in string.letters ]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
>>> [ dig for dig in string.digits ]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>>
Yes paramiko can do that. You mentioned that you can do it from the command line. So why not just use system commands via python?
I.E. os.system, or popen, subprocess, etc. ?
Did the windows and mac have the same versions of Python installed? What version were you using by the way?
If you search this forum you'll find lots of good examples of how to use pygame. Either that or your friendly google portal to the web.
The input buffer works exactly as any other type of buffer. It fills up with whatever it is reading and stores the information until you read it.
read(size=x) reads x number of bytes from the buffer.
inWaiting() tells you how many bytes are in the buffer waiting to be read
flushInput() clears the buffer and discards all of its contents.
Read over the pyserial informational wiki and you'll see much information to help you. A big concern of mine is how you've set up your serial port. Make sure you set the proper parameters (Baud rate, non-blocking, etc.). Again, pay attention to the wiki page for more details on this.
This is strange. I'm getting
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python25\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python25\lib\pickle.py", line 1198, in load_setitem
dict[key] = value
TypeError: 'str' object does not support item assignment
The object that you pickled, did it require any special classes?
Also, are you saying that you pickled one object on a Mac, and one on a Windows box, and are trying to unpickle both on the Windows box now?
Couldn't you just read(x); x number of bytes into some garbage variable?
If you search this forum for pygame you will find tons of examples of games that our forums members have creating using said module.
Either that or google.
Also, have you tried self.SetAutoLayout(True)
?
Here's how to ask for input:
Built-in functions
Look down the page... there are two input methods. See if you can find them.
So... where's your code? Where are your errors? Please read the posting guidelines, and get to know them. If you follow the posting guidelines we can actually help you.
We have actually noticed that python records and prints the input to the pins of the microcontroller before the code is executed in python. Hence, it does not record and print new inputs once the code was been executed.
I'm kinda confused by that statement... could you explain a little further, maybe provide an example of expected input -> output, and actual input -> output?
My Code goes here!
import serial,csv,sys
print('Tactile Sensing Feedback for Medical Palpation in MIS\n Pyserial Testing Module\n')
ch= raw_input("Enter a to initialize pyserial module, b to quit:")if ch == 'a':
print 'Initializing Pyserial module'
ser = serial.Serial(0,baudrate=57600,timeout=0,xonxoff=0)
print ser.portstr
ser.flushInput()for x in range (0,100):
s = ser.readline()
print repr(s)
ser.close()elif ch == 'b':
print 'closing port......\n'
quit()else:
print 'Invalid option please input a or b only'
LOL
1) Don't use the <> characters on the language... it would just be code=python
2) Put your code in place of the "My code goes here!" part.
Kind of sounds like dependency issues... but seeing as that module is built into Python I don't see how this could happen.
I tried importing those modules (which I've never used before) and they worked. Perhaps you need a reinstallation of Python.
Ah, now it makes slightly more sense...
First things first: to remove an item from a list:
>>> mathches = [ 1,2,3,4,5 ]
>>> mathches.remove(3)
>>> mathches
[1, 2, 4, 5]
>>>
also, instead of nothing = 0
; which I'm assuming is just there for the syntax you could use pass
. Or simply reverse your logic and do away with a second case:
if not letter in matches[c]:
matches.remove(c)
That way you don't even need to worry about an else case. Because really you should never need a "do nothing here" line in your code.
You can look into paramiko for FTP use. I've used it before and it's VERY straight forward. The documentation provides plenty of examples of usage for connecting to an FTP server and retrieving files.
If you look at the top right-hand side of the page you will find this white box contained in a larger green box. It's called a search box and it's very useful...
Also, vegaseat gave us all a very nice example of using fancy text and the like in the sticky post about wxPython... Take the time to do a little digging and you'll find your answer.
Here's one method to open and read a file:
f = open( 'myfile.txt', 'r' ) # 'r' is for Read Mode
lines = f.readlines()
f.close()
# Now lines contains a list of each line of the file contents
for eachline in lines:
# Add line to wx.*ctrl