OS X: Determine Trash location for a given path
Simply moving the file to ~/.Trash/
will not work, as if the file os on an external drive, it will move the file to the main system drive..
Also, there are other conditions, like files on external drives get moved to /Volumes/.Trash/501/
(or whatever the current user's ID is)
Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python
Asked by: Caroline566 | Posted: 28-01-2022
Answer 1
Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code here via RubyCocoa. The the gist of it is:
url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete
You could easily do something similar with PyObjC.
Answered by: Darcy301 | Posted: 01-03-2022Answer 2
Based upon code from http://www.cocoadev.com/index.pl?MoveToTrash I have came up with the following:
def get_trash_path(input_file):
path, file = os.path.split(input_file)
if path.startswith("/Volumes/"):
# /Volumes/driveName/.Trashes/<uid>
s = path.split(os.path.sep)
# s[2] is drive name ([0] is empty, [1] is Volumes)
trash_path = os.path.join("/Volumes", s[2], ".Trashes", str(os.getuid()))
if not os.path.isdir(trash_path):
raise IOError("Volume appears to be a network drive (%s could not be found)" % (trash_path))
else:
trash_path = os.path.join(os.getenv("HOME"), ".Trash")
return trash_path
Fairly basic, and there's a few things that have to be done seperatly, particularly checking if the filename already exist in trash (to avoid overwriting) and the actual moving to trash, but it seems to cover most things (internal, external and network drives)
Update: I wanted to trash a file in a Python script, so I re-implemented Dave Dribin's solution in Python:
from AppKit import NSURL
from ScriptingBridge import SBApplication
def trashPath(path):
"""Trashes a path using the Finder, via OS X's Scripting Bridge.
"""
targetfile = NSURL.fileURLWithPath_(path)
finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
items = finder.items().objectAtLocation_(targetfile)
items.delete()
Usage is simple:
trashPath("/tmp/examplefile")
Answered by: Emily391 | Posted: 01-03-2022
Answer 3
A better way is NSWorkspaceRecycleOperation, which is one of the operations you can use with -[NSWorkspace performFileOperation:source:destination:files:tag:]. The constant's name is another artifact of Cocoa's NeXT heritage; its function is to move the item to the Trash.
Since it's part of Cocoa, it should be available to both Python and Ruby.
Answered by: Ada627 | Posted: 01-03-2022Answer 4
In Python, without using the scripting bridge, you can do this:
from AppKit import NSWorkspace, NSWorkspaceRecycleOperation
source = "path holding files"
files = ["file1", "file2"]
ws = NSWorkspace.sharedWorkspace()
ws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, "", files, None)
Answered by: Aston905 | Posted: 01-03-2022
Answer 5
The File Manager API has a pair of functions called FSMoveObjectToTrashAsync and FSPathMoveObjectToTrashSync.
Not sure if that is exposed to Python or not.
Answered by: Ted715 | Posted: 01-03-2022Answer 6
Another one in ruby:
Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete
You will need rb-appscript gem, you can read about it here
Answered by: Oliver484 | Posted: 01-03-2022Similar questions
python - Determine location of laptop based on WiFi
Say, I want to determine the location of the local machine 192.168.1.2 connected on my network. I want to find the "relative"/"absolute" ( any would do, relative is better though) of the laptop.
Is there a way to do it? WiFi based location searching (the most common answer that popped up when I searched for this) is based on position triangulation which means, the code I will run will tell me my location and not o...
python - Badoo repeat - How to determine and keep track of user's location in IOS?
I want to do the following.
Keep updating a user's location using Core Location and send that information to a database.
I am creating an app like badoo so I need to know where a user is located at all times to know who is near them.
I did the following:
I put the following code in applicationDidFinishLaunchWithOptions
locationManager = [[CLLocationM...
python - Determine location of laptop based on WiFi
Say, I want to determine the location of the local machine 192.168.1.2 connected on my network. I want to find the "relative"/"absolute" ( any would do, relative is better though) of the laptop.
Is there a way to do it? WiFi based location searching (the most common answer that popped up when I searched for this) is based on position triangulation which means, the code I will run will tell me my location and not o...
python - Badoo repeat - How to determine and keep track of user's location in IOS?
I want to do the following.
Keep updating a user's location using Core Location and send that information to a database.
I am creating an app like badoo so I need to know where a user is located at all times to know who is near them.
I did the following:
I put the following code in applicationDidFinishLaunchWithOptions
locationManager = [[CLLocationM...
How to determine location where python code is called if it is stored in different location
Let's say I'm calling a python file from this directory:
$ pwd
$ my_dir1/path1/
$ python mydir2/path2/my_code.py
Note that my_code.py is stored at another directory.
What I want to do is in my_code.py determine where it is called.
Namely I want it to display my_dir1/path1/.
What code should I put in my_code.py.
weather - How to determine what city I'm in using my mac's location and python?
I'm trying to create a basic weather web app. The idea is that it will automatically determine your location and then display the forecast for that area. I'm sure this has already been done, I'm just doing it for fun. Are there any python libraries or ways of doing this? Upon googling for a solution, I couldn't find anything. On stack overflow the only similar question is related to android.
python - Determine Caller Location by Command on PATH
If I have a python application installed on my system, is there a way for that application to determine where the call is being executed from?
For example, if the app "myApp" is installed at Users/myUsr/python/site-packages, and the app is called from, say, /foo/bar/, could the app determine the caller's location on the file system?
In other words:
$ # pwd fr...
python - How to determine if a directory is on same partition
Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?
What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:
target_directory = "/Volumes/externalDrive/something/"
input_foldername, input_filename = os.path.split(input_file)
if same_partition(input_folde...
python - How can you determine a point is between two other points on a line segment?
Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.
How can you determine if another point c is on the line segment defined by a and b?
I use python most, but examples in any language would be helpful.
python - How do I determine if an email is Base64 encoded?
I am having difficulty determining if the body of a text email message is base64 encoded.
if it is then use this line of code;
making use of jython 2.2.1
dirty=base64.decodebytes(dirty)
else continue as normal.
This is the code I have atm. What line of code will allow me to extract this from the email:
"Content-Transfer-Encoding: base64"
import email, ...
python - How do I determine all of my IP addresses when I have multiple NICs?
I have multiple Network Interface Cards on my computer, each with its own IP address.
When I use gethostbyname(gethostname()) from Python's (built-in) socket module, it will only return one of them. How do I get the others?
macos - How to determine number of files on a drive with Python?
I have been trying to figure out how to retrieve (quickly) the number of files on a given HFS+ drive with python.
I have been playing with os.statvfs and such, but can't quite get anything (that seems helpful to me).
Any ideas?
Edit: Let me be a bit more specific. =]
I am writing a timemachine-like wrapper around rsync for various reasons, and would like a very fast estimate...
Determine if a function is available in a Python module
I am working on some Python socket code that's using the socket.fromfd() function.
However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined.
What's the best way to determine if a method is defined at runtime? Is the...
How do I determine if an object has an attribute in Python?
How do I determine if an object has some attribute? For example:
>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
How do I tell if a has the attribute property before using it?
code analysis - Tool to determine what lowest version of Python required?
Is there something similar to Pylint, that will look at a Python script (or run it), and determine which version of Python each line (or function) requires?
For example, theoretical usage:
$ magic_tool <EOF
with something:
pass
EOF
1: 'with' statement requires Python 2.6 or greater
$ magic_tool <EOF
class Something:
@classmethod
def blah(cls):
pass
EOF
2: classmethod requi...
python - How can I determine the monitor refresh rate?
Is there a cross platform way to get the monitor's refresh rate in python (2.6)? I'm using Pygame and PyOpenGL, if that helps.
I don't need to change the refresh rate, I just need to know what it is.
How to determine whether java is installed on a system through python?
Using Python, I want to know whether Java is installed.
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python