Re: how to find the directory of the current python script

Posted by Aryeh Weiss on
URL: http://imagej.273.s1.nabble.com/how-to-find-the-directory-of-the-current-python-script-tp5023449p5023452.html

On 07/06/2020 23:10, Wayne Rasband wrote:
>> On Jun 7, 2020, at 2:25 PM, Aryeh Weiss <[hidden email]> wrote:
>>
>> I am running a Python script form the Fiji script editor, an d need to be able to import another python function that lives in the same directory.
> The ImageJ 1.53c18 daily build adds an IJ.getDir("file”) method that returns the directory of the most recently opened or saved file. It is similar to the File.directory() macro function. Note that IJ.getDir() is just another name for IJ.getDirectory(). Here is an example:
>
>    IJ.log("This script was loaded from "+IJ.getDir("file"));
>
> -wayne

Thank you for your quick reply.

I tried this, running from the Fiji script editor.

######

import os
from os import sys

from ij import IJ

print("os.cwd gives: ", os.getcwd())    # Nicholas George's response
(thank you)
print('getDir("file") gives: ', IJ.getDir("file"))     # Wayne's response

#######

The output of the run after starting Fiji:

('os.cwd gives: ', '/home/amw')
('getDir("file") gives: ', u'/home/amw/Desktop/Fiji.app/macros/AutoRun/')

and after opening some image:

Started fileTest.py at Mon Jun 08 05:38:55 IDT 2020
('os.cwd gives: ', '/home/amw')
('getDir("file") gives: ', u'/home/amw/Pictures/')

Best regards
--aryeh


>
>
>> The brute force way is:
>>
>> sys.path.append(os.path.abspath("/home/amw/Desktop/projects/alerding/summer2020"))
>> from  prune_new import prune
>>
>> but I do not want a script that relies on that absolute path.
>>
>> So I tried variations of IJ.getDirectory("current") and such, and none of them produce the correct result.
>>
>> I can do:
>>
>> sys.path.append(IJ.getDirectory(""))
>> from  prune_new import prune
>>
>> and select the directory, but that is annoying to do every run.
>>
>> I found a solution for macros in this forum post:
>> https://forum.image.sc/t/does-anyone-have-an-elegant-way-to-id-the-folder-a-macro-is-run-from/7924?u=herbie
>>
>> where Wayne provided File.directory() for macros. I have not found the API way to do this for a python script.
>>
>> Is there a way to do it?
>>
>> Thanks in advance
>> --aryeh
> --
> ImageJ mailing list: http://imagej.nih.gov/ij/list.html


--
Aryeh Weiss
Faculty of Engineering
Bar Ilan University
Ramat Gan 52900 Israel

Ph:  972-3-5317638
FAX: 972-3-7384051

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html