简体   繁体   English

从finder执行时,python重命名脚本不起作用(Mac)

[英]python rename script not working when executed from finder (Mac)

Helly everyone, 大家好

I'm kind of new to python, but I have written a little script that helps me rename file extensions. 我是python的新手,但是我写了一个小脚本来帮助我重命名文件扩展名。 It's very short, so I'll post it here: 它很短,所以我将其发布在这里:

import os

for filename in os.listdir("."):
    if filename.endswith("gd"):
        os.rename(filename, filename + ".dat")

Now, as I have several directories I need to execute this in, it was getting kind of annoying to always navigate to the folder in terminal and execute it from there using the commmand 现在,由于我有几个目录需要在其中执行,所以总是导航到终端中的文件夹并使用命令从那里执行它变得很烦人

python renamescrip.py

Now I stumbled across some advice that would make a python script execute upon double clicking in the Finder, which would make life a lot easier for me, as I would just need to copy and paste the renamescript.py into the folder in which I want to rename the files and double click on it to execute it. 现在,我偶然发现了一些建议,这些建议将使Finder中双击python脚本即可执行,这对我来说使工作变得更加轻松,因为我只需要复制并粘贴namedname.py到我想要的文件夹中重命名文件,然后双击执行它。

I followed these instructions: http://skillfulness.blogspot.de/2010/12/how-to-run-python-script-from-mac-os-x.html , which show how to create a .command file. 我遵循了以下指示信息: http : //skillfulness.blogspot.de/2010/12/how-to-run-python-script-from-mac-os-x.html ,其中显示了如何创建.command文件。

However, when I double clicked the renamescript.command file, it didn't change the file names in the directory. 但是,当我双击renamescript.command文件时,它没有更改目录中的文件名。

I also tried opening the .py file with Python Launcher, but that also didn't change the filenames. 我还尝试使用Python启动器打开.py文件,但这也没有更改文件名。

Both times a terminal window opened, though, with the message: 但是,两次都打开了终端窗口,并显示以下消息:

cd '/path to directory with files to rename/' && '/usr/local/bin/pythonw'  '/path to directory with files to rename/renamescript.py' && echo Exit status: $? && exit 1
Exit status: 0
logout

or if I click on the .command file it's just: 或者,如果我单击.command文件,它只是:

/path to directory with files to rename/renamescript.command ; exit;
logout

What am I doing wrong? 我究竟做错了什么?

When you double click, you are not running with the same directory form your current directory as when you run from the shell. 双击时,您使用的当前目录与从Shell运行时所在的目录不同。 This causes your os.listdir(".") to not find the files you think it should. 这会使os.listdir(".")找不到您认为应该的文件。 You should change your directory at the beginning of your script with 您应该在脚本开头使用以下命令更改目录

os.chdir(os.path.dirname(os.path.abspath(__file__)))

before your os.listdir call 在您的os.listdir调用之前

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

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