I write this script
import urllib
urllib.urlretrieve("URL","path\ name.jpg")
It's working
But if there is no internet it's make wrong
I want it if there is no internet. wait to connect by internet then work again
You can write something like this:
def wait_for_internet_connection():
while True:
try:
response = urllib2.urlopen('http://google.com',timeout=1)
return
except urllib2.URLError:
pass
def main():
#your code here
wait_for_internet_connection()
main()
The while loop will execute until there's an active internet connection, then executes your code.
Related
I am trying to use GLib.IOChannels to send data from a client to a server running a Glib.Mainloop.
The file used for the socket should be located at /tmp/so/sock, and the server should simply run a function whenever it receives data.
This is the code I've written:
import sys
import gi
from gi.repository import GLib
ADRESS = '/tmp/so/sock'
def server():
loop = GLib.MainLoop()
with open(ADRESS, 'r') as sock_file:
sock = GLib.IOChannel.unix_new(sock_file.fileno())
GLib.io_add_watch(sock, GLib.IO_IN,
lambda *args: print('received:', args))
loop.run()
def client(argv):
sock_file = open(ADRESS, 'w')
sock = GLib.IOChannel.unix_new(sock_file.fileno())
try:
print(sock.write_chars(' '.join(argv).encode('utf-8'), -1))
except GLib.Error:
raise
finally:
sock.shutdown(True)
# sock_file.close() # calling close breaks the script?
if __name__ == '__main__':
if len(sys.argv) > 1:
client(sys.argv[1:])
else:
server()
When called without arguments, it acts as the server, if called with arguments, it sends them to a running server.
When starting the server, I immediately get the following output:
received: (<GLib.IOChannel object at 0x7fbd72558b80 (GIOChannel at 0x55b8397905c0)>, <flags G_IO_IN of type GLib.IOCondition>)
I don't know why that is. Whenever I send something, I get an output like (<enum G_IO_STATUS_NORMAL of type GLib.IOStatus>, bytes_written=4) on the client side, while nothing happens server-side.
What am I missing? I suspect I understood the documentation wrong, as I did not find a concrete example.
I got the inspiration to use the IOChannel instead of normal sockets from this post: How to listen socket, when app is running in gtk.main()?
Trying to create a program that runs 24x7 in the background and undertakes actions triggered by change in the up/down i.e connected/disconnected state of the ethernet adapter port in PCs/Laptops. How to implement the same in Python?
For ex:
conn = True
def conCheck()
if conn == False:
<trigger onward events>
else:
<else statements>
Any help will be greatly appreciated. Trying to take up and learn python.
Thanks and regards
You can write a function that can request a web page for checking the internet connection.
If there is no internet, You might be getting a ConnectionError.
Otherwise, You'll get a response from the URL. i.e. You're connected with the internet.
Use the following code & try to interrupt the connection your code is executing. You'll see the difference when your internet gets interrupted.
import time
import requests
url = "http://www.kite.com"
timeout = 5
conn = True
def conCheck():
try:
request = requests.get(url, timeout=timeout)
print("Connected to the Internet")
return True
except (requests.ConnectionError, requests.Timeout) as exception:
print("You're not connected to the internet. ")
return False
while True:
conCheck()
time.sleep(1)
When I run a local host server to view my html files, I usually use the command line prompt:
python -m http.server 8000
However, I want to be able to do this from within a .py file, and I'm struggling.
Ideally when running the py file it should launch the server, open the localhost in the default web browser, and then remain open until the user types in a keyword, like 'exit'. As per the http.server documentation, my current code looks like this:
import http.server
import socketserver
import webbrowser
PORT = 8000
URL = f'localhost:{PORT}/MapViz.html'
def run():
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("Enjoy your visualization!")
httpd.serve_forever()
if __name__ == "__main__":
run()
webbrowser.open_new(URL)
I know at the moment it has nothing to close the server after the user is done, but I'm just struggling to get it to open the browser first. It seems like serve_forever() is not the right tool for the job, but I'm not sure what is.
Also, do I need to worry about closing the socket? I've always been able to use a with open(x) as file: format for files to not worry about closing them, but I had an issue while messing with this where I got a Windows error 10048, stating that the socket was still being used, so maybe it's also not closing correctly.
Thank you!
Here is the solution I am using!
import http.server
import socketserver
import webbrowser
import threading
import sys
PORT = 8000
URL = f'http://localhost:{PORT}/MapViz.html'
def run():
Handler = http.server.SimpleHTTPRequestHandler
global httpd
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Enjoy your visualization!")
httpd.serve_forever()
def maintain():
webbrowser.open_new(URL)
while True:
user_input = input()
if user_input == 'EXIT' or user_input == 'exit':
print('Shutting down! Run this .exe again to view your visualization again.')
threading.Timer(0.1, httpd.shutdown).start()
break
if __name__ == '__main__':
threading.Timer(1.0, maintain).start()
run()
I tweaked the code Michael gave me ever so slightly and had threading.Timer call an entirely new function, which both opened the window in a browser and checked for the kill-word.
I am sure my shutdown is not the most efficient way, but does what I need it to. I will definitely need to look into more threading examples to find how best
I'm trying to write a simple smtp server program. I've written a simple smtp client (in C#) which sends an email. I've tested the program with smtp4dev. So far it all works fine.
I'd also like to write my own simple program which receives the email (instead of smtp4dev). I've tried a number of different code snippets (eg: Here) that I've found around the web but I can't seem to get them working.
I've also tried using twisted.
To start with I can see using TCPView that the port numbers in the code are not the ones being used.
I get the feeling that I'm missing something conceptual though and heading in the wrong direction.
EDIT
Here's the C# code in case you are interested
MailMessage mail = new MailMessage();
mail.Subject = "Your Subject";
mail.From = new MailAddress("test#test.com.au");
mail.To.Add("soslab#soslab.lab");
mail.Body = "Hello! your mail content goes here...";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("LOCALHOST", 26);
smtp.EnableSsl = false;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
here's the python code
import smtpd
import asyncore
class EmailServer(smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
print 'a'
def run():
foo = EmailServer(('localhost', 26), None)
try:
asyncore.loop()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
run()
For some reason this program runs fine when I run it from the command line
import smtpd
import asyncore
import winsound
class PYEmailServer(smtpd.SMTPServer):
def __init__(*args, **kwargs):
smtpd.SMTPServer.__init__(*args, **kwargs)
def process_message(self, peer, mailfrom, rcpttos, data):
winsound.Beep(2500, 1000)
def run():
foo = PYEmailServer(('localhost', 26), None)
try:
asyncore.loop()
except KeyboardInterrupt:
foo.close()
if __name__ == '__main__':
run()
It does not work when I run it from IDLE. (C# program just throws an exception like the service isnt there). I dont know why this would be, but I have my original problem working.
To test your smtp server you need to set the smtpclient object on another terminal
import smtplib
smtpclient=smtplib.SMTP('127.0.0.1',8001)
smtpClient.sendmail('sender#gmail.com','recivers#gmail.com','sadfsdf')
I'm creating a game in the Blender Game Engine. And I have coded an IRC script which works fine on OS X and Linux distros. The output is similar to this:
Logging in...
LOGIN_ERROR
LOGIN_ERROR
LOGIN_ERROR
LOGIN_ERROR
LOGIN_ERROR
LOGIN_ERROR
<name> has joined.
Logged in!
And then I can call my sendmsg() function to send messages to the IRC channel.
This is the error I get when I try to run on Windows 7:
My python IRC code:
http://pastebin.com/aG6TwTir
Ignore the "bge" references. Those variables and such are filled from the game engine.
In the game engine, I call login() once, and it spits out "LOGIN_ERROR" so I know it's trying to connect, and then it will connect, therefore not throwing an exception and ending the function.
In OS X and Linux, it runs perfectly and seemlessly in the background while the player can continue to play as it connects.
In windows 7, it throws that error.
So I guess what needs to happen is a way to wait for the script to connect to the server. Then once connected, I can send the login information and join the channel.
So how do I wait for the connection?
FYI: I have the sockets non-blocking, since the script needs to run on the same thread as the game engine, on every frame.
Main() is run every frame, not the whole script. At the menu, it executes the script and calls login(). Then once in the game, it will call Main() every frame.
Oh and I'm using Python 3.3.
Any help is greatly apreciated! ^_^
EDIT:
How do I handle this exception?
This code:
def login():
...
try:
...
except:
...
login() # <===
recursively calls itself; given a high enough number of login failures, depending on the stack size limit (which depends on platform I guess), you'll get a stack overflow.
See also: Setting stacksize in a python script
Although I would always just avoid recursion and use looping instead, unless I know in advance that the recursion depth will never be more than ~100:
while True:
try:
do_login()
except: # NOTE: USE A SPECIFIC EXCEPTION CLASS HERE, BTW
continue
else:
break
You have recursion happening in your error handling
def login():
#print('login')
# Bind the socket
try:
s.connect((HOST, PORT))
# Send login info
s.send(bytes('NICK %s\r\n' % NICK, 'UTF-8'))
s.send(bytes('USER %s %s bla :%s\r\n' % (IDENT, HOST, REALNAME), 'UTF-8'))
s.send(bytes('JOIN %s\r\n' % CHAN, 'UTF-8'));
print('Logging in...')
chatlog('Logging in...')
except:
print('LOGIN_ERROR')
login()
So in your function login() you have a try, then in the except you call login() again. This will just loop over and over again if the login fails.