从Python运行shell命令和字符串连接

1 投票
3 回答
2270 浏览
提问于 2025-04-16 21:51

我正在尝试调整“发布到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
0

其他回答已经给出了这个问题的核心内容:在你的命令周围加上引号,使用格式化字符串来插入值,并考虑使用子进程来真正获取命令的输出。

不过,如果你和我一样觉得这个过程有点复杂,可以看看这个例子,它展示了如何在Python中实际进行网址缩短。如果你是Python新手,这可能意味着你需要了解一下异常处理的相关内容,以便理解这个过程。(看起来你可能还需要一个自定义模块,但似乎只有在出现异常时才会用到...)

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)

撰写回答