从Python运行shell命令和字符串连接
我正在尝试调整“发布到Dropbox”的服务,适用于Snow Leopard(http://dl.dropbox.com/u/1144075/Post%20to%20Dropbox.zip)。我不想要公共链接,而是想要一个来自goo.gl的缩短链接。
为此,我使用了这些命令:
curl -s --data-urlencode "url=http://link.com" http://googl/action/shorten | grep "googl" | awk -F\" '{print $(NF-1)}' | awk 'BEGIN { FS = "=" } ; { print $2}' | pbcopy
现在这个Python脚本会将它刚刚复制到公共文件夹的所有文件的Dropbox链接复制到剪贴板:
pasteURLs = []
for file in copied_files: # for all elements in our list
components = file.split(os.sep) # seperate the path
local_dir = os.sep.join(components[5:]) # cut off the beginning
local_dir = urllib.quote(local_dir) # convert it to a URL (' ' -> '%20', etc.)
#construct the URL
finalURL = 'http://dl.dropbox.com/u/%s/%s' % ( dropbox_id, local_dir )
pasteURLs.append(finalURL) # add the current URL to the string
copy_string = "\n".join(pasteURLs)
os.system( "echo '%s' | pbcopy" % (copy_string) ) # put the string into clipboard
我得承认我对Python一无所知,但从表面上看,我需要把最后两行改成这样:
shortURL = []
for thisURL in pasteURLs:
shortURL = os.system( curl -s --data-urlencode "url=http://link.com" http://googl/action/shorten | grep "goo.gl" | awk -F\" '{print $(NF-1)}' | awk 'BEGIN { FS = "=" } ; { print $2}' | pbcopy )
shortURLs.append(shortURL)
copy_string = "\n".join(shortURLs)
os.system( "echo '%s' | pbcopy" % (copy_string) ) # put the string into clipboard
但我遇到的问题是,怎么把正确的链接放到命令里?如你所见,它写的是 http://link.com
,但应该用 thisURL
来替代。
有什么想法吗?提前谢谢!
3 个回答
0
更新 我为你写了一个脚本,并使用了一个更简单的命令流程。其实整个过程可以用Python来完成,而不需要用到curl,但我还是把它写出来了。
import subprocess
thisURL = 'http://whatever.com'
pipeline = []
pipeline.append('curl -s -i --data-urlencode "url=%s" ' % thisURL +
'http://goo.gl/action/shorten')
pipeline.append('grep Location:')
pipeline.append('cut -d = -f 2-')
#pipeline.append('pbcopy')
command = "|".join(pipeline)
link, ignore = subprocess.Popen(command, stdout=subprocess.PIPE,
shell=True).communicate()
print link
1
我觉得你的os.system调用应该像这样:
os.system("curl -s --data-urlencode \"url=%s\" http://goo.gl/action/shorten | grep \"goo.gl\" | awk -F\\\" '{print $(NF-1)}' | awk 'BEGIN { FS = \"=\" } ; { print $2}' | pbcopy " % thisURL)