简体   繁体   中英

How to find the directory of the .app that a python script is running from

I recently made a python script that goes through files in whatever directory it is placed in and renames them based on certain criteria. The script works perfectly, and I compiled the script into an OS X .app using py2app. This worked fine as well. However now when I run the script, it searches through the files in the ".app/contents/macOS" folder (where the script is located) rather than where the ".app" is actually located.

This is because it has this code at the start:

src = os.path.dirname(os.path.abspath(__file__))

which assigns the the location of the ".py" file to a variable which is then used extensively throughout the script. Is there any way I can instead add a snippet of code which tells python the path location of the ".app" that the ".py" file is executing from?

If not, perhaps there is a way to get a file explorer window open, from there it would be possible for a user to select a folder who's path would then get assigned to the "src" variable. I'm very new to python however so this would certainly be a challenge.

Try to use:

import os
print(os.getcwd())

From docs:

getcwd()

Return a unicode string representing the current working directory.

To find the location of the .app directory that wraps the application, the most direct way is to modify the path that you find with your current code. After computing src as you did, just trim it like this and use app as the path:

import re
...
app, rest = re.split(r"/[^/]*\.app/", src, 1)

This stops at the first path component that ends in .app . If you prefer you can hard-code your application name, eg /myprogram.app/ .

PS. I'm puzzled as to why you copy your app to the folder you want to modify. A file selection dialog, or drag and drop, is the more common (and easier) way to tell a program what to work on. OS X applications created with py2app support drag and drop: Your program can get the path to the dropped directory like this:

import sys
folders = sys.argv[1:]   # Handles multiple arguments
for folder in folders:
    do_something_in(folder)

Then simply drag and drop the directory or directories you want to process onto the application icon, which you can just keep on your desktop, the Finder's sidebar, or a favorite directory -- no need to copy it each time you use it, and no need for it to know where its source is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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