Python Script to Copy Current Directory Path (and Optionally, IP address) to Clipboard on OS X

15 Oct 2009
Posted by Jeet Sukumaran

I find this very useful:

#! /usr/bin/env python
 
############################################################################
##  cpwd.py
##
##  Copies current directory path (and, optionally, external IP address) 
##  to clipboard, stripping line-break.
##
##  Copyright 2008 Jeet Sukumaran.
##
##  This program is free software; you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation; either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License along
##  with this programm. If not, see <http://www.gnu.org/licenses/>.
##
############################################################################
 
"""
The problem with "pwd | pbcopy" is that the newline gets appended to the end
of the string. Sed ("pwd | sed 's/\n\\g' | pbcopy") does not work, because
sed adds its own newline. This script takes care of this problem ...
"""
 
import os
import sys
import subprocess
import socket
 
def get_external_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("www.google.com",80))
    ipaddr, port = s.getsockname()
    return ipaddr
 
path = os.path.abspath(os.path.curdir)
p1 = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
path = path.replace(' ', '\ ')
if len(sys.argv) > 1 and (sys.argv[1] == "--ip" or sys.argv[1] == "-i"):
    path = "%s:%s" % (get_external_ip(), path)
p1.stdin.write(path)
sys.stdout.write("Sent to clipboard: %s\n" % path)
Tags:

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a biological visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.