简体   繁体   English

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

[英]Python - find and replace - copy result to clipboard in Automator

I have a python script working perfectly when executed from terminal. 从终端执行时,我有一个python脚本可以正常工作。 But when trying to go through automator i just get "Run Shell Script" error. 但是,当尝试通过自动程序时,我只会收到“运行Shell脚本”错误。

Goal: (mind you, complete noob here, hence the 'noob' task) In my day job (different discipline) im always collaborating with people on windows and mac alike. 目标:(请注意,在这里完成noob,因此是“ noob”任务)在我的日常工作(不同的纪律)中,我总是与Windows和Mac上的人们进行协作。 Im on a mac, so trying to make a quick right click drop down service to retrieve the files path > find /, replace with \\ and also the difference in beginning of server path > copy to clipboard. 我在Mac电脑上,因此尝试进行快速右键单击下拉服务以检索文件路径>查找/,替换为\\,以及服务器路径开头>复制到剪贴板的区别。 This way giving someone a windows version of the path is a click and paste away. 通过这种方式,给某人提供Windows版本的路径就是单击并粘贴。 scripting 101 im sure. 脚本101即时通讯。

Its all great on my .py doc through terminal...obviously give's me the path of my doc, looking great so far. 通过终端在我的.py文档上一切都很好...很显然为我提供了我的文档路径,到目前为止看起来很棒。 To mobilize this thing i heard Automator is a great way to do so. 我听说Automator是动员这件事的好方法。

I get the specified error when set up: Run Shell Script Shell: /usr/bin/python Pass Input: as arguments. 设置时出现指定的错误: 运行Shell脚本 Shell:/ usr / bin / python通过输入:作为参数。 Code: 码:

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)

Ive also simply tried using Shell: /bin/bash and directing it to the .py with the same result. Ive也只是尝试使用Shell:/ bin / bash并将其定向到.py,结果相同。 There's a lot of guess work here so i can only imagine all of the way this is wrong. 这里有很多猜测工作,所以我只能想象这是错误的所有方式。 But, it does work in terminal, so i feel i cant be too far off. 但是,它确实可以在终端上工作,所以我觉得我离得太远了。

All help is greatly appreciated. 非常感谢所有帮助。

Without going into detail, this worked for me on Snow Leopard. 无需赘述,这对我在Snow Leopard上起作用。 You can test it, if you put a Finder 'Ask for Finder Item' Dialogue in front. 如果将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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM