Skip to main content
 首页 » 编程设计

Python之查找和替换之将结果复制到 Automator 中的剪贴板

2025年05月04日12lyhabc

我有一个 python 脚本在从终端执行时运行良好。但是当试图通过自动机时,我只是得到“运行 Shell 脚本”错误。

目标:(请注意,这里是完全菜鸟,因此是“菜鸟”任务)在我的日常工作(不同学科)中,我总是与 Windows 和 Mac 上的人合作。我在 Mac 上,因此尝试快速右键单击下拉服务以检索文件路径 > 查找/,替换为\以及服务器路径开头的差异 > 复制到剪贴板。通过这种方式,只需单击并粘贴即可为某人提供 Windows 版本的路径。脚本 101 我确定。

通过终端在我的 .py 文档上一切都很棒......显然给我提供了我的文档的路径,到目前为止看起来很棒。为了动员这件事,我听说 Automator 是一个很好的方法。

设置时出现指定错误:运行 Shell 脚本 Shell:/usr/bin/python 传递输入:作为参数。代码:

import os 
 
def replace_all(text, dic): 
    for i, j in dic.iteritems(): 
        text = text.replace(i, j) 
    return text 
 
userlink = os.path.realpath(__file__) 
 
reps = {'/':'\\','///':'\\', 'rr1mgsfile46':'gameshare\\share\\IEBDesign','smb:':''} 
 
txt = replace_all(userlink, reps) 
 
 
cmd = 'echo %r | tr -d "\n" | pbcopy' % txt 
os.system(cmd) 

我也简单地尝试使用 Shell:/bin/bash 并将其定向到 .py,结果相同。这里有很多猜测工作,所以我只能想象这是错误的。但是,它确实适用于终端,所以我觉得我离得太远了。

非常感谢所有帮助。

请您参考如下方法:

无需详细说明,这对我在 Snow Leopard 上很有效。你可以测试它,如果你把 Finder 的“询问 Finder 项目”对话放在前面。

import sys 
import os 
 
def replace_all(text, dic): 
    for i, j in dic.iteritems(): 
        text = text.replace(i, j) 
    return text 
 
for userlink in sys.argv[1:]: 
    # print('pbcopy ' + userlink) # this is for testing 
    os.system('pbcopy ' + f) 
    reps = {'/':'\\','///':'\\', 'rr1mgsfile46':'gameshare\\share\\IEBDesign','smb:':''} 
    txt = replace_all(userlink, reps) 
 
    cmd = 'echo %r | tr -d "\n" | pbcopy' % txt 
    os.system(cmd)