Skip to content

Instantly share code, notes, and snippets.

@bennr01
Last active April 2, 2019 13:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bennr01/37cb294c005ff7fd95a079f644331555 to your computer and use it in GitHub Desktop.
Save bennr01/37cb294c005ff7fd95a079f644331555 to your computer and use it in GitHub Desktop.
Use the Pythonista App to open an URL on your PC
"""
Open an URL on pc.
You need to configure pythonista to run this script when "open in" is used.
Replace YOUR_HOST_OR_IP with your ip or hostname.
"""
#!python2
import socket
import appex
HOST = "YOUR_HOST_OR_IP" # host/IP to connect to
PORT = 22222 # port to connect to
def send_url(url):
"""send an URL on your PC."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IPv4 TCP socket
s.settimeout(5) # try at most 5 seconds
s.connect((HOST, PORT)) # connect to HOST/PORT
s.send(url) # send url
s.close() # close connection
def main():
"""main function."""
urls = appex.get_urls() # get all urls used for "open in"
if len(urls) == 0:
print("No URLs found!")
for url in urls:
print("Opening: " + url)
send_url(url)
if __name__ == "__main__":
# ensure main() is only called when run manually
main()
"""server for opening URLs in your webbrowser."""
import socket
import webbrowser
PORT = 22222 # Port to listen on. USe 0 for auto.
HOST = "0.0.0.0" # host/IP to listen on. In this case, any and all interfaces available
def open_url(url):
"""open an url in your webbrowser."""
# open the url in a webbrowser. use a new tab (new=2) and send the window to foreground.
webbrowser.open(url, new=2, autoraise=True)
def main():
"""the main function."""
listen_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create a IPv4 TCP socket
listen_s.bind((HOST, PORT)) # bind to HOST/PORT
listen_s.listen(1) # listen for connections, max backlog 1
own_addr = listen_s.getsockname() # get socket address, in case the port was automatically determined
print("Listening on: " + repr(own_addr))
while True:
print("Waiting for connection...")
conn, addr = listen_s.accept() # wait for a connection and accept
print("New connection from: " + repr(addr))
url = conn.recv(8192) # receive up to 8192 bytes.
print("Opening: " + url)
open_url(url) # open the url
conn.close() # close the connection
print("Connection closed.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment