[Tutor] Help understanding classes
Hello everyone, hope all is well. Was just wondering if I could get some help understanding classes and how they work. What is the point in OOP if I don¹t understand classes, are classes not the heart and soul of OOP? I have been trying to learn classes by practicing with Tkinter building GUIs. Below is my code, which does work. It simply opens a window. I just don¹t understand why it works? Where would the rest of my code go(after I write it of course)? Say, I added code to do something in the window; for example, if I wanted to add buttons and if a button was clicked, execute some linux commands and display the output in the window? I don¹t understand where that code would go. I can easily execute linux commands using subprocess, psutil, os, and even commands, but how does that all work together with classes? I feel like all the code I have written thus far is very linear and simple, and if I can grasp classes I can get out of this stagnate slump. Thank you in advance. from Tkinter import * class test(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title(³TestApp") self.pack(fill=BOTH, expand=1) def main(): root = Tk() root.geometry("250x150+300+300") app = test(root) root.mainloop() if __name__ == '__main__': main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] I apologize
I accidentally sent my last email from my work email. I recently added my gmail account to MS exchange and I forget I have to change where I send the mail from now that I have two accounts in exchange. Sorry for any confusion. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Nested loop of I/O tasks
Dear Python I am new to Python and having questions about its usage. Currently I have to read two .csv files INCT and INMRI which are similar to this INCT NONAME 121.57 34.71 14.81 1.35 0 0 1 Cella 129.25 100.31 27.25 1.35 1 1 1 Chiasm 130.3 98.49 26.05 1.35 1 1 1 FMagnum 114.89 144.94 -15.74 1.35 1 1 1 Iz 121.57 198.52 30.76 1.35 1 1 1 LEAM 160.53 127.6 -1.14 1.35 1 1 1 LEAM 55.2 124.66 12.32 1.35 1 1 1 LPAF 180.67 128.26 -9.05 1.35 1 1 1 LTM 77.44 124.17 15.95 1.35 1 1 1 Leye 146.77 59.17 -2.63 1.35 1 0 0 Nz 121.57 34.71 14.81 1.35 1 1 1 Reye 91.04 57.59 6.98 1.35 0 1 0 INMRI NONAME 121.57 34.71 14.81 1.35 0 0 1 Cella 129.25 100.31 27.25 1.35 1 1 1 Chiasm 130.3 98.49 26.05 1.35 1 1 1 FMagnum 114.89 144.94 -15.74 1.35 1 1 1 Iz 121.57 198.52 30.76 1.35 1 1 1 LEAM 160.53 127.6 -1.14 1.35 1 1 1 LEAM 55.2 124.66 12.32 1.35 1 1 1 LPAF 180.67 128.26 -9.05 1.35 1 1 1 LTM 77.44 124.17 15.95 1.35 1 1 1 Leye 146.77 59.17 -2.63 1.35 1 0 0 My job is to match the name on the two files and combine the first three attributes together. So far I tried to read two files. But when I tried to match the pattern using nested loop, but Python stops me after 1 iteration. Here is what I got so far. INCT = open(' *.csv') INMRI = open(' *.csv') for row in INCT: name, x, y, z, a, b, c, d = row.split(",") print aaa, for row2 in INMRI: NAME, X, Y, Z, A, B, C, D = row2.split(",") if name == NAME: print aaa The results are shown below "NONAME" "NONAME" "Cella " "NONAME" "Chiasm" "NONAME" "FMagnum" "NONAME" "Inion" "NONAME" "LEAM" "NONAME" "LTM" "NONAME" "Leye" "NONAME" "Nose" "NONAME" "Nz" "NONAME" "REAM" "NONAME" "RTM" "NONAME" "Reye" "Cella" "Chiasm" "FMagnum" "Iz" "LEAM" "LEAM" "LPAF" "LTM" "Leye" "Nz" "Reye" I was a MATLAB user and am really confused by what happens with me. I wish someone could help me with this intro problem and probably indicate a convenient way for pattern matching. Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Any stuff about python interpreter design ?
Hello , I have learned and used python half a year , and I like this language very much . I used it in my web server page , in my homework and part-tiem job . Recently , I feel very interested in the python interpreter . So I take a look into the source code .But I get confused about so many files and functions . I want to ask that is there any stuff about the interpreter design and coding ? Thanks in advance ! Regards ! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Any stuff about python interpreter design ?
Danny Yoo said: >> So I take a look into the source code .But I get confused about so many >> files and functions . I want to ask that is there any stuff about the >> interpreter design and coding ? >> > > [meta: my reply is really about Scheme, not Python. My apologies to the > list, but it's my honest answer.] > > Hi Bo, > > There are several books and online material about the writing of > interpreters. The ones that I'm most aware aware of that are aimed at > beginner programmers, though, target the language 'Scheme'. The core > Scheme language has a fairly minimal syntax and semantics, and it's simple > enough that it's not too bad for beginner to understand (and write!) a > usable Scheme interpreter. > > So you may find it useful to learn about interpreters by looking at Scheme > interpreters. And even though it's not Python, it's still very related > and applicable; if you have a model of how a Scheme interpreter works, > you'll be better equipped to understand in general how interpreters work. > > > For example, the textbook "How to Design Programs": > > http://www.htdp.org/ > > starts covering the evaluation of a programming language by about Chapter > 14: > > http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-19.html#node_sec_14.4 > > > Here are other Scheme resources about interpretation (the first two links > contain online books): > > http://mitpress.mit.edu/sicp/ > http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/ > http://www.cs.indiana.edu/eopl/ > http://www-spi.lip6.fr/~queinnec/WWW/LiSP.html > > If you have more questions, please feel free to ask! > > > I feeled the people in this mailing list are very really friendly , I will follow your links and ask again if I have any questions ! Regards ! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with erros using subprocess module
Jerome Jabson 写道: > Hi, > > I've been trying to write a wrapper around some shells > scripts using the subprocess module. But I'm getting > errors I quite don't know how to debug. I've only been > writing Python for a few months and starting processes > are new to me. Here's my code: > > import os > import re > import subprocess > > > Definition > > > def proc(cmd_in): >cmd = cmd_in >os.chdir("/home/qauser/jerome") >outFile = os.path.join(os.curdir, "output.log") >outptr = file(outFile, "w") >errFile = os.path.join(os.curdir, "error.log") >errptr = file(errFile, "w") >retval = subprocess.call(cmd, 0, None, None, > outptr, errptr) >errptr.close() >outptr.close() >if not retval == 0: > errptr = file(errFile, "r") > errData = errptr.read() > errptr.close() > raise Exception("Error executing command: " + > repr(errData)) > > def setup(): >print "=== Starting Setup ===" >proc("/home/qauser/jerome/qaSetup.sh") >print "=== Setup Complete ===" > > def run_junit(): >file_in = > open("/home/qauser/automation/testdata/junit_master_file", > "r") > Could you put the contents in the junit_master_file here ? Are the first field in every line where the cmd name locates contain the full path to the command ? >match = re.compile('#+') >work_list = [] >for line in file_in: > work = line > work = work.rstrip('\n') > if match.search(work): > found = False > else: > found = True > if found == True: > work_list = work.split(',') > arg1 = work_list[0] > arg2 = work_list[1] > arg3 = work_list[2] > arg4 = work_list[3] > cmd = "/home/qauser/jerome/qaRun.sh %s %s %s > %s" > cmdstr = cmd % (arg1,arg2,arg3,arg4) > print "=== Starting JUnit Run ===" > proc(cmdstr) > print "=== JUnit Run Complete ===" > > > > ## Main ## > > > setup() > run_junit() > > The setup() def seems to work great, but the > run_junit() seems to have problems. I believe due to > the params I'm passing. Here are the errors I'm > getting: > > [EMAIL PROTECTED] automation]$ ./runJunit.py > === Starting JUnit Run === > Traceback (most recent call last): > File "/home/qauser/automation/runJunit.py", line 63, > in ? > run_junit() > File "/home/qauser/automation/runJunit.py", line 54, > in run_junit > proc(cmdstr) > File "/home/qauser/automation/runJunit.py", line 18, > in proc > retval = subprocess.call(cmd, 0, None, None, > outptr, errptr) > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 412, in call > return Popen(*args, **kwargs).wait() > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 542, in __init__ > errread, errwrite) > File > "/opt/python-2.4.3/lib/python2.4/subprocess.py", line > 975, in _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I can't seem to figure out what file or directory is > missing. > > Your help is greatly appreciated, > Jerome > > __ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] list comprehension equivalent to map(function, list item)
i have the following simple function that iterates over the list. It passes the list item into the function and adds the numbers. What would be the equivalent way of writing the "map" portion with list comprehension? My code is as follows: def add(number): print 1 + int(number) x = ['2', '4', '6', '8', '10', '12'] map(add, x) thanks for the help and thank you for this mailing list. AngryNinja ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension equivalent to map(function, list item)
Thank you for your assistance. Based on your direction, I figured it out. *This... * def add(number): print 1 + int(number) x = ['2', '4', '6', '8', '10', '12'] [add(item) for item in x] *Is the same as... * def add(number): print 1 + int(number) x = ['2', '4', '6', '8', '10', '12'] map(add, x) They both yield the same results. Is there a benefit to using one way over the other? In larger computations, does one way calculate faster or is it merely a preference? Again, thank you. AngryNinja On Fri, Dec 13, 2013 at 9:24 PM, Amit Saha wrote: > On Sat, Dec 14, 2013 at 11:03 AM, Bo Morris wrote: > > i have the following simple function that iterates over the list. It > passes > > the list item into the function and adds the numbers. What would be the > > equivalent way of writing the "map" portion with list comprehension? My > code > > is as follows: > > > > def add(number): > > print 1 + int(number) > > > > > > > > x = ['2', '4', '6', '8', '10', '12'] > > > > map(add, x) > > Think of a list comprehension as: > > [ dosomething(item) for item in alist] > > And, comparing it with your map implementation, here is what you get: > > >>> [1+int(item) for item in x] > [3, 5, 7, 9, 11, 13] > > > Here, dosomething(item) corresponds to 1+int(item). > > Hope that helps. > > -Amit. > > > -- > http://echorand.me > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Quantum computing (Alan Gauld)
Haha guess we all have to become quantum physicist! This type of computing is still just a theory, is it not? I found this to be interesting.. ."First, there’s the question of knowing if it’s even working in the first place. A widely known tenet of quantum mechanics is that merely observing the phenomenon changes the outcome of an event. So, watch a quantum particle, or a qubit, or anything quantum for that matter, and you change its behaviour. That means that it’s actually very difficult to tell if a quantum computer is behaving in the way we’d expect or need it to." *quoted from http://www.gizmodo.com.au/2013/12/whats-wrong-with-quantum-computing/ On Sat, Dec 14, 2013 at 4:36 AM, wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-requ...@python.org > > You can reach the person managing the list at > tutor-ow...@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > >1. Re: weird lambda expression -- can someone help meunderstand > how this works (Steven D'Aprano) >2. Quantum computing (David Hutto) >3. Re: Tutor Digest, Vol 118, Issue 62 (Keith Winston) >4. Re: list comprehension equivalent to map(function,list item) > (Bo Morris) >5. Re: weird lambda expression -- can someone help me understand > how this works (Alan Gauld) >6. Re: Quantum computing (Alan Gauld) > > > -- > > Message: 1 > Date: Sat, 14 Dec 2013 15:21:45 +1100 > From: Steven D'Aprano > To: tutor@python.org > Subject: Re: [Tutor] weird lambda expression -- can someone help me > understand how this works > Message-ID: <20131214042144.GP29356@ando> > Content-Type: text/plain; charset=us-ascii > > On Sat, Dec 14, 2013 at 12:29:54PM +1000, Amit Saha wrote: > > > Consider this simple example: > > > > >>> l = lambda x: x**2 > > >>> apply(l, (3,)) > > 9 > > The built-in function apply is deprecated in Python 2 and removed in > Python 3. Instead apply, you should use argument unpacking: > > l(*(3,)) > > In this case, it's silly to unpack a tuple of a single value, instead > you should just do this: > > l(3) > > > -- > Steven > > > -- > > Message: 2 > Date: Fri, 13 Dec 2013 23:36:37 -0500 > From: David Hutto > To: "tutor@python.org" > Subject: [Tutor] Quantum computing > Message-ID: > < > ca+vvgjw63imaqsp52+ererkvztcpm55i+ri68xoicpcje_n...@mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Recently, after having some personal problems, I've returned to looking at > the future of not only prototyping languages like python, but also the more > advanced/older(refinement of your computers resources) languages. > > > My main question/topic, is what is to become of languages like python with > the emergence of quantum computing? > > How will python evolve to meet the needs of these newr technologies > intertwining into the marketplace? > > We know the richest get it first, but how do we begin to even simulate, and > evolve to meet the needs of tomorrows world of advanced computing, and will > the instruction sets of these newer technologies effect us considerably? > > Just to kick off a topic. > -- > Best Regards, > David Hutto > *CEO:* *http://www.hitwebdevelopment.com <http://www.hitwebdevelopment.com > >* > -- next part -- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131213/cd7a9eef/attachment-0001.html > > > > -- > > Message: 3 > Date: Fri, 13 Dec 2013 23:25:28 -0500 > From: Keith Winston > To: tutor@python.org > Subject: Re: [Tutor] Tutor Digest, Vol 118, Issue 62 > Message-ID: > fcdk5pz3n4b_x3xp+...@mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > > > > Message: 6 > > Date: Thu, 12 Dec 2013 23:10:31 -0500 > > From: Sky blaze > > To: tutor@python.org > > Subject: [Tutor] Coding for a Secret Message in a Game > > > > > > it'd be amusing to have the message change after the player types > something > > other than "start" at least 10 times. I've
[Tutor] interacting with stderr
Here is my working code. It works great in the lab, but I still need to test it on a live system. I also need to add the email notifications to it, but I purposely left them out for now; I will also adjust the sleep time to a more appropriate amount. Anyone see any issues with it or ways to make it better? #!/usr/bin/env python import subprocess from subprocess import PIPE import time import psutil import sys count = 0 restart = 0 def kill_proc(process1, process2): i = psutil.Popen(["ps", "cax"], stdout=PIPE) out, err = i.communicate() for proc in psutil.process_iter(): if proc.name == process1 and process2: proc.kill() while True: while count < 15: count += 1 kill_proc("bmdplay", "avconv") print "Starting the script", count time.sleep(2) p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in p.stderr: print line if "Segmentation" in line: kill_proc("bmdplay", "avconv") while restart < 3: restart += 1 time.sleep(2) p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in p.stderr: print line if restart == 3: # send email saying so sys.exit() if "storing 0x" in line: kill_proc("bmdplay", "avconv") while restart < 3: restart += 1 sleep.time(2) p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in p.stderr: print line if restart == 3: # send email saying so sys.exit() if count == 10: print "Going to sleep, will try again in..." #send email saying so time.sleep(2) if count == 15: # send email saying so print "Gave up" break break ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] command counter
how would I keep track of count for each time a command exectuted? for example... subprocess.Popen("command") && add 1 to count. If count equals n number, do something. I have tried count = 0 count += 1, but count does not seem to be incrementing. Thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] command counter
I think I figured it out... each time I run subprocess.Popen("command"), I also have to count += 1, which adds 1 to count each time the command is run. Is this correct, or is there a better way? Thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] command counter
Here is the shell script I am trying to recreate in python. Sorry for not posting this with my other emails...I am a bit off today. restart_count=10 count=10 restart=5 while ((count--)); do avconv -v verbose -re -analyzeduration 0 | ./bmdplay -m 2 -f pipe:0 echo "Retry" if [[ $count = 1 ]] && [[ $restart != 1 ]]; then sleep 10 ((restart--)) count=$restart_count fi done echo "Gave up" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] printing all text that begins with "25"
Hello all, hope everyone is doing well. When I run the linux command "hamachi list" i get something along the lines of the following output 087-888-279 Pandora25.x.x.xxx alias: not set 096-779-867 AM1LaptopBD-PC25.x.x.xxx alias: not set 097-552-220 OWS-Desktop 125.0.0.0 alias: not set 099-213-641 DESKTOP 25.0.0.0 alias: not set I am trying to write a python script that will run the above command and only print out the IP's that begin with 25. How do I strip out all other text except for the IP's that begin with "25?" Would it be best to send to a file first, then read the contents of the file? Would I need to use regex? I know how to run the above command in python. I also know how to send the output to a file and read the file; however I cannot figure out how to strip all text out except for the IPs that begin with "25." Thanks PS...Danny, still working on the "root" problem we discussed in previous emails. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Insert time into email
hello all, hope everyone is doing well. The below code works, however I am going back and trying to enter the time and date and I cant quite figure out how to do this without breaking the code. #!/usr/bin/python import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage import time strFrom = "HourlyReport.com" #strTo = "engineer...@oneconnxt.com" #strTo = "mmed...@onemediacorpinc.com" strTo = "b...@onemediacorpinc.com" l = ['3102EHD-01108.png', '3102DHD-01109.png','3102EHD-01082.png', '3102DHD-01033.png', '3102EHD-01302.png', '3102DHD-01149.png', '3102EHD-01125.png', '3102DHD-01144.png', '3102EHD-01105.png'] t = time.strftime("%H:%M:%S") d = time.strftime("%d/%m/%Y") msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Test Hourly Report' msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) msgText = MIMEText('TIMEDATETIMEDATETIMEDATETIMEDATETIMEDATETIMEDATETIMEDATETIMEDATETIMEDATE', 'html') msgAlternative.attach(msgText) for image in l: with open(image, 'rb') as fh: msgImage = MIMEImage(fh.read()) msgImage.add_header('Content-ID', '<{0}>'.format(image)) msgRoot.attach(msgImage) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(strFrom, strTo, msgRoot.as_string()) print "Successfully sent email" except smtplib.SMTPException: print "Error: unable to send email" I need to enter the time and date in the html where "TIME" and "DATE" are. I imagine I can do this by adding "cid: t" and "cid:d" which just refers back to t = "time.strftime("%H:%M:%S")" "d = time.strftime("%d/%m/%Y")"? Thanks in advance for any help. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Insert time into email...final code
Just in case anyone else can benefit from this, here is my working code up to this point #!/usr/bin/python import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage import time strFrom = "HourlyReport.com" strTo = "myem...@server.com" t = time.strftime("%H:%M:%S %m/%d/%y") l = ['3102EHD-01108.png', '3102DHD-01109.png','3102EHD-01082.png', '3102DHD-01033.png', '3102EHD-01302.png', '3102DHD-01149.png', '3102EHD-01125.png', '3102DHD-01144.png', '3102EHD-01105.png'] msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Test Hourly Report' msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) msgText = MIMEText('3102EHD-01108{time}3102DHD-01109{time}3102EHD-01082{time}3102DHD-01033{time}3102EHD-01302{time}3102DHD-01149{time}3102EHD-01125{time}3102DHD-01144{time}3102EHD-01105{time}'.format(time=t), 'html') msgAlternative.attach(msgText) for image in l: with open(image, 'rb') as fh: msgImage = MIMEImage(fh.read()) msgImage.add_header('Content-ID', '<{0}>'.format(image)) msgRoot.attach(msgImage) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(strFrom, strTo, msgRoot.as_string()) print "Successfully sent email" except smtplib.SMTPException: print "Error: unable to send email" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Code critique
Hello all, May I please get a little instructional criticism. The code below works. It logs into 9 different Linux computers, runs a couple commands, and then transfers a file back to the server. I want to become a better Python coder; therefore, I was hoping for some ways to make the below code better, more efficient, or if I am doing something incorrectly, a correct way of doing it. Thanks #!/usr/bin/python import paramiko l = ['ip-1', 'ip-2', 'ip-3', 'ip-4', 'ip-5', 'ip-6', 'ip-7', 'ip-8', 'ip-9'] def connect(ip): user = 'user' passwd = '' command = 'echo $HOSTNAME' s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(ip,22,user,passwd,timeout=4) stdin, stdout, stderr = s.exec_command('echo $HOSTNAME') out = stdout.read() if '3102EHD-Lanka-1108' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01108/3102EHD-01108.png', '/Downloads/Hourly/3102EHD-01108.png') sftp.close() print 'file recieved' elif '3102EHD-01109' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102DHD-01109/3102DHD-01109.png', '/Downloads/Hourly/3102DHD-01109.png') sftp.close() print 'file recieved' elif '3102EHD-MUTV-1082' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01082/3102EHD-01082.png', '/Downloads/Hourly/3102EHD-01082.png') sftp.close() print 'file recieved' elif '3102DHD-MUTV-1033' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102DHD-01033/3102DHD-01033.png', '/Downloads/Hourly/3102DHD-01033.png') sftp.close() print 'file recieved' elif 'Encoder' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01302/3102EHD-01302.png', '/Downloads/Hourly/3102EHD-01302.png') sftp.close() print 'file recieved' elif '3102DHD-01149' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102DHD-01149/3102DHD-01149.png', '/Downloads/Hourly/3102DHD-01149.png') sftp.close() print 'file recieved' elif '3102EHD-01125' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01125/3102EHD-01125.png', '/Downloads/Hourly/3102EHD-01125.png') sftp.close() print 'file recieved' elif '3102DHD-01144' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102DHD-01144/3102DHD-01144.png', '/Downloads/Hourly/3102DHD-01144.png') sftp.close() print 'file recieved' elif '3102EHD-01105' in out: s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01105/3102EHD-01105.png', '/Downloads/Hourly/3102EHD-01105.png') sftp.close() print 'file recieved' con = map(connect, l) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Code critique
"...Regarding your program, instead of writing long sequences of repetitive if conditions, I would write one function for each of the different operations and store them in a dict, mapping each host name to a function (and multiple host names may map to the same function). Then, look up the host name in the dict and call the corresponding function to run the right operations on that host..." Thank you Stefan for your input. Would please be willing to provide an example? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Code critique
Thank you all for the helpful criticism. I wish I was able to catch on to what you are suggesting more quickly. Based on your recommendations, I have come up with the following so far, however I just dont see it as easily as I did while using the if/elif statements. This is what I have so far. I can not figure out how to iterate through the dictionary inserting each value where "png_file" should be and execute the code for each ip address in the list. I was able to do it using the if/elif statements, but I am afraid I am lost trying to do it another way. ipList = ['ip-1', 'ip-2', 'ip-3', 'ip-4', 'ip-5', 'ip-6', 'ip-7', 'ip-8', 'ip-9'] host = {'3102EHD-01108':'3102EHD-01108.png', '3102EHD-01109':'3102DHD-01109.png', '3102EHD-MUTV-1082':'3102EHD-01082.png', '3102DHD-01033':'3102DHD-MUTV-1033.png', 'Encoder':'3102EHD-01302.png', '3102DHD-01149':'3102DHD-01149.png', '3102EHD-01125':'3102EHD-01125.png', '3102DHD-01144':'3102DHD-01144.png', '3102EHD-01105':'3102EHD-01105.png'} # iterate through the dictionary inserting the png file def get_png_file(?): process = get_png_file.get(hostname, png_file) s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/'png_file,'/Downloads/Hourly/'png_file) sftp.close() print 'file recieved' user = 'user' passwd = 'password' s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # iterate through the list and do the below for each for ip in ipList: s.connect(ip,22,user,passwd,timeout=4) since I have all the hostnames in the dic, and I am removing the if/elif statments, do I need the below command 'echo $HOSTNAME'? stdin, stdout, stderr = s.exec_command('echo $HOSTNAME') out = stdout.read() get_png_file(?) **original code below** #connect to each machine and retrieve the image# l = ['ip-1', 'ip-2', 'ip-3', 'ip-4', 'ip-5', 'ip-6', 'ip-7', 'ip-8', 'ip-9'] def connect(ip): user = 'user' passwd = 'password' command = 'echo $HOSTNAME' s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(ip,22,user,passwd,timeout=4) stdin, stdout, stderr = s.exec_command('echo $HOSTNAME') out = stdout.read() if '3102EHD-Lanka-1108' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01108/3102EHD-01108.png', '/Downloads/Hourly/3102EHD-01108.png') sftp.close() elif '3102EHD-01109' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102DHD-01109/3102DHD-01109.png', '/Downloads/Hourly/3102DHD-01109.png') sftp.close() elif '3102EHD-MUTV-1082' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01082/3102EHD-01082.png', '/Downloads/Hourly/3102EHD-01082.png') sftp.close() elif '3102DHD-MUTV-1033' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102DHD-01033/3102DHD-01033.png', '/Downloads/Hourly/3102DHD-01033.png') sftp.close() elif 'Encoder' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01302/3102EHD-01302.png', '/Downloads/Hourly/3102EHD-01302.png') sftp.close() elif '3102DHD-01149' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102DHD-01149/3102DHD-01149.png', '/Downloads/Hourly/3102DHD-01149.png') sftp.close() elif '3102EHD-01125' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01125/3102EHD-01125.png', '/Downloads/Hourly/3102EHD-01125.png') sftp.close() elif '3102DHD-01144' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102DHD-01144/3102DHD-01144.png', '/Downloads/Hourly/3102DHD-01144.png') sftp.close() elif '3102EHD-01105' in out: s.exec_command('export DISPLAY=:0.0; /Downloads/Hourly/win.sh') sftp = s.open_sftp() sftp.get('/Downloads/Hourly/3102EHD-01105/3102EHD-01105.png', '/Downloads/Hourly/3102EHD-01105.png') sftp.close() con = map(connect, l) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Practicing with sockets
Hello all, hope everyone is doing well. I have been practicing with sockets and I am trying to send a small png from the client to the server. the client code is... import socket f = open('/Users/Bo/Desktop/logo_ONEConnxt.png', 'rb') strf = f.read() client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("ip.ip.ip.ip", 8999)) client_socket.sendall(strf) f.close() exit() and the server code is... import socket f = open('img.png', 'wb') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 8999 s.bind(('', port)) s.listen(5) client_socket, address = s.accept() data = client_socket.recv(4029) f.write(data) client_socket.close() Both the above client and server code runs without error, however the "img.png" file that is placed on the server shows zero bytes? Will someone please show me what I am doing wrong? Thank you, Bo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Practicing with sockets
Hey Danny, yes I have been having quite a bit of fun learning to work with sockets. Thank you for your response. I have applied what you suggested with the exception of the "logging." I read through the logging docs and figured logging would be learning for another day. I have a hard time enough staying focused on one task at time haha. I did however insert some print statements into the code so I could keep track of where it was at, but to keep my email short, I omitted them here. After implementing what you suggested, the image fie that is saved on the server is now 4 bytes, but I assume that is due to... "Your client code will symmetrically read the first four bytes, use struct.unpack() to find how how large the rest of the message is going to be, and then do a loop until it reads the exact number of bytes" and I have not quite got the correct loop to read all the bytes? I also reread the docs at https://docs.python.org/2/howto/sockets.html and decided to remove the "b" from "open('myfile.png', 'wb') open('myfile.png', 'rb') seeing how binary could be different depending on the machine and I have not yet learned how to deal with this. Would I be better off converting the image to base64 prior to sending it to the server, then decoding it on the server? Here is my updated code...for brevity sake, I have omitted the "import" statments... Client: f = open('/Users/Bo/Desktop/SIG.png', 'r') strf = f.read() client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("ip,ip,ip,ip", 8999)) payload = client_socket.send(struct.pack("!I", len(strf))) for data in payload: client_socket.sendall(strf) f.close() exit() Server: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 8999 s.bind(('', port)) s.listen(5) client_socket, address = s.accept() data = client_socket.recv(4029) f = open('img.png', 'w') for item in data: f.write(item) f.flush() f.close() client_socket.close() At least I am getting 4 bytes in oppose to 0 like I was getting before. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Practicing with sockets
ok so I finally got all the bytes to be transfered to the server, however I am unable to open the image on the server; although the filed is saved as a png file on the server, the server does not recognize the file as png format? I changed the loops to the following... Client: f = open('/Users/Bo/Desktop/SIG.png', 'r') strf = f.read() client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("25.78.28.110", 8999)) while True: client_socket.send(struct.pack("!I", len(strf))) data = client_socket.sendall(strf) if not data: break f.close() print "Data Received successfully" exit() Server: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 8999 s.bind(('', port)) s.listen(5) client_socket, address = s.accept() f = open('img.png', 'w') while True: data = client_socket.recv(4029) f.write(data) if not data: break #f.flush() f.close() client_socket.close() On Fri, Oct 31, 2014 at 3:42 PM, Bo Morris wrote: > Hey Danny, yes I have been having quite a bit of fun learning to work with > sockets. Thank you for your response. I have applied what you suggested > with the exception of the "logging." I read through the logging docs and > figured logging would be learning for another day. I have a hard time > enough staying focused on one task at time haha. I did however insert some > print statements into the code so I could keep track of where it was at, > but to keep my email short, I omitted them here. > > After implementing what you suggested, the image fie that is saved on the > server is now 4 bytes, but I assume that is due to... > > "Your client code will symmetrically read the first four bytes, use > struct.unpack() to find how how large the rest of the message is going to > be, and then do a loop until it reads the exact number of bytes" > > and I have not quite got the correct loop to read all the bytes? > > I also reread the docs at https://docs.python.org/2/howto/sockets.html and > decided to remove the "b" from "open('myfile.png', 'wb') open('myfile.png', > 'rb') seeing how binary could be different depending on the machine and I > have not yet learned how to deal with this. Would I be better off > converting the image to base64 prior to sending it to the server, then > decoding it on the server? > > Here is my updated code...for brevity sake, I have omitted the "import" > statments... > > Client: > > f = open('/Users/Bo/Desktop/SIG.png', 'r') > strf = f.read() > client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > client_socket.connect(("ip,ip,ip,ip", 8999)) > payload = client_socket.send(struct.pack("!I", len(strf))) > for data in payload: > client_socket.sendall(strf) > f.close() > exit() > > Server: > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > port = 8999 > s.bind(('', port)) > s.listen(5) > client_socket, address = s.accept() > data = client_socket.recv(4029) > f = open('img.png', 'w') > for item in data: > f.write(item) > f.flush() > f.close() > client_socket.close() > > At least I am getting 4 bytes in oppose to 0 like I was getting before. > > > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help understanding classes
Thank you Alan and Danny. It amazes me at the lengths you guys, as well as everyone else who contributes, will go to to help explain things to us; it is greatly appreciated! Alan, I decided to dumb down the learning classes just a little. By this I mean, I am not using Tkinter to learn classes. I am using one of the examples from your website, which I did change it just a little. I figured, I am having a hard time wrapping my head around classes and Tkinter would just add to the confusion. So, I have the below code. When I run this from terminal, it obviously prints "This is a test." If I may, break the code down and ask questions as it pertains to the code? # class Message: def __init__(self, aString): self.text = aString def printIt(self): print self.text m = Message("This is a test") m.printIt() ## With the first part... class Message: def __init__(self, aString): self.text = aString Will I always use "_init_" when defining the first function in a class? I noticed on your website, you created a class where you did not use "_init_" (see below). Was this because you did not define a function? class BalanceError(Exception): value = "Sorry you only have $%6.2f in your account" I noticed that I can change "text" to anything and I still get the same results by running the code; I changed them to "blah" just as a test. When I define a function in a class, will I always use "self" as the first entry in the parenthesis? On the next part... m = Message("This is a test") m.printIt() I noticed I cannot run "printIt()" unless I make it an object i.e. "m = Message("This is a test")...?" I noticed I could change "m = Message("This is a test")" to "m = Message(raw_input())," which works. What if I wanted to create a function in Message that receives text from another function and then prints that text instead of the text from "m = Message("This is a test")...; can I pass or return values to another function inside a class? The"self" is really throwing me off, when I think about creating different functions that do misc things just to practice. For example, I have a function that kills a Linux program. I just don't see how to rethink that function to where it could be defined in a class? def kill_proc(process1): i = psutil.Popen(["ps", "cax"], stdout=PIPE) for proc in psutil.process_iter(): if proc.name(process1): proc.kill() Would it be something like...? class processKiller: def _init_(self): def kill_proc(self, process1): i = psutil.Popen(["ps", "cax"], stdout=PIPE) for proc in psutil.process_iter(): if proc.name(process1): proc.kill() Then outside of the class, call it like so...? p = processKiller() p.proc.kill() Again, I am just practicing, trying to wrap my head around classes and understand how to create and use them. Oh yeah, Alan I preordered your new book maybe a month or so ago. Any word on when it will be released and shipped? Again, thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Projects
The book arrived this morning. Thanks Alan! Bo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm
On Thu, Jun 15, 2017 at 12:52:10PM +, Neil Cerutti wrote: On 2017-06-14, Peter Otten <__pete...@web.de> wrote: Sebastian Silva wrote: Or shorter: if unit in 'Cc': Don't do that. You are in for nasty surprises: def check(unit): ... if unit in "Cc": ... return "Celsius" ... return "unknown" ... check("c") 'Celsius' check("C") 'Celsius' check("F") 'unknown' Fine so far. But now: check("Cc") 'Celsius' check("") 'Celsius' In fact, check("cC") 'unknown' Best Woah! I bet I've got that bug in several of my programs. Thanks! -- Neil Cerutti ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] delete strings from specificed words
Hi, I am learning python to reslove issue,which make happy:) But, i am facing an interesting question.I have no idea to deal with it. The text i will working as follow: ```text [PATCH] perf tools: Fix copyfile_offset update of output offset We need to increase output offset in each iteration, not decrease it as we currently do. I guess we were lucky to finish in most cases in first iteration, so the bug never showed. However it shows a lot when working with big (~4GB) size data. Link: http://lkml.kernel.org/n/tip-f4az7t2nxjbjz5tqrv83z64e@xx Signed-off-by: Jiri Olsa --- tools/perf/util/util.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/perf/util/util.c b/tools/perf/util/util.c index a789f952b3e9..443892dabedb 100644 --- a/tools/perf/util/util.c +++ b/tools/perf/util/util.c @@ -210,7 +210,7 @@ static int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size -= ret; off_in += ret; - off_out -= ret; + off_out += ret; } munmap(ptr, off_in + size); -- 2.13.6 ``` In fact, this is a patch from lkml,my goal is to design a kernel podcast for myself to focus on what happened in kernel. I have crawled the text with python and want to remove strings from *diff --git*, because reading the git commit above, i have a shape in head. I have tried split(), replace(), but i have no idea to deal with it. I will appericate if you have any idea. Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] delete strings from specificed words
Hi, First, thank you very much for your reply. On Tue, Jan 09, 2018 at 10:25:11PM +, Alan Gauld via Tutor wrote: On 09/01/18 14:20, YU Bo wrote: But, i am facing an interesting question.I have no idea to deal with it. I don;t think you have given us enough context to be able to help much. WE would need some idea of the input and output data (both current and desired) It sounds like you are building some kind of pretty printer. Maybe you could use Pythons pretty-print module as a design template? Or maybe even use some of it directly. It just depends on your data formats etc. Yes. I think python can deal with it directly. In fact, this is a patch from lkml,my goal is to design a kernel podcast for myself to focus on what happened in kernel. Sorry, I've no idea what lkml is nor what kernel you are talking about. Can you show us what you are receiving, what you are currently producing and what you are trying to produce? Some actual code might be an idea too. And the python version and OS. Sorry, i don't to explain it.But, my code is terribly. lkml.py: ```code #!/usr/bin/python # -*- coding: UTF-8 -*- # File Name: lkml.py # Author: Bo Yu """ This is source code in page that i want to get """ import sys reload(sys) sys.setdefaultencoding('utf8') import urllib2 from bs4 import BeautifulSoup import requests import chardet import re # import myself print function from get_content import print_content if __name__ == '__main__': comment_url = [] target = 'https://www.spinics.net/lists/kernel/threads.html' req = requests.get(url=target) req.encoding = 'utf-8' content = req.text bf = BeautifulSoup(content ,'lxml') # There is no problem context = bf.find_all('strong') for ret in context[0:1]: for test in ret: print '\t' x = re.split(' ', str(test)) y = re.search('"(.+?)"', str(x)).group(1) comment_url.append(target.replace("threads.html", str(y))) for tmp_target in comment_url: print "===This is a new file ===" print_content(tmp_target, 'utf-8', 'title') ``` get_content.py: ```code #!/usr/bin/python # -*- coding: UTF-8 -*- # File Name: get_content.py import urllib2 from bs4 import BeautifulSoup import requests import chardet import re def print_content(url, charset, find_id): req = requests.get(url=url) req.encoding = charset content = req.text bf = BeautifulSoup(content ,'lxml') article_title = bf.find('h1') #author = bf.find_all('li') commit = bf.find('pre') print '\t' print article_title.get_text() print '\t' x = str(commit.get_text()) print x ``` python --version: Python 2.7.13 OS: debian 9 usage: python lkml.py output: oh... https://pastecode.xyz/view/04645424 Please ignore my print debug format. This is my code and i can get text like output above. So, simple my quzz: I dont know how to delete strings after special word, for example: ```text The registers rax, rcx and rdx are touched when controlling IBRS so they need to be saved when they can't be clobbered. diff --git a/arch/x86/entry/calling.h b/arch/x86/entry/calling.h index 45a63e0..3b9b238 100644 ... ``` I want to delete string from *diff --git* to end, because too many code is here Whatever, thanks! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] delete strings from specificed words
Hi, On Wed, Jan 10, 2018 at 10:37:09AM +0100, Peter Otten wrote: YU Bo wrote: index 45a63e0..3b9b238 100644 ... ``` I want to delete string from *diff --git* to end, because too many code is here Use str.split() or str.partition() and only keep the first part: text = """The registers rax, rcx and rdx are touched when controlling IBRS ... so they need to be saved when they can't be clobbered. ... ... diff --git a/arch/x86/entry/calling.h b/arch/x86/entry/calling.h ... index 45a63e0..3b9b238 100644 ... """ cleaned_text = text.partition("diff --git")[0].strip() print(cleaned_text) The registers rax, rcx and rdx are touched when controlling IBRS so they need to be saved when they can't be clobbered. Cool,It is what i want. Thanks all! Bo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] delete strings from specificed words
Hi, On Thu, Jan 11, 2018 at 11:40:35AM +1100, Cameron Simpson wrote: On 09Jan2018 22:20, YU Bo wrote: The text i will working as follow: ```text [...] diff --git a/tools/perf/util/util.c b/tools/perf/util/util.c index a789f952b3e9..443892dabedb 100644 [...] +++ b/tools/perf/util/util.c [...] ``` [...] I have tried split(), replace(), but i have no idea to deal with it. Do you have the text as above - a single string - or coming from a file? I'll presume a single string. En.., the text is multi-string from str(something) within python. I would treat the text as lines, particularly since the diff markers etc are all line oriented. So you might write something like this: interesting = [] for line in the_text.splitlines(): if line.startswith('diff --git '): break interesting.append(line) Now the "interesting" list has the lines you want. Yes, i test your method and it will come to my intend, but maybe cast a few of other steps. I think that the method will offer a similar ways to solve others issues. I personally like peter's method: text.partition("diff --git")[0].strip() Thanks, Bo There's any number of variations on that you might use, but that should get you going. Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Trouble with SUM()
Hi, I'm trying to write a program that uses a while loop to ask a user for multiple values then use the program to add all the values, however many there may be, then print the sum. I'm having trouble with the sum() function. My code is below: con = "y" while con == "y": AMT = float(input("What is the price of the item? $")) con = input("Would you like to continue? [y/n]") price = float(sum(AMT + AMT)) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor