[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