Find File Path of a Given Class

How do I get the filepath for a class in Python?

You can use the inspect module, like this:

import inspect
inspect.getfile(C.__class__)

Find file path of a given class

Use source_location on its methods:

YourClass.instance_methods(false).map { |m| 
YourClass.instance_method(m).source_location.first
}.uniq

You might get more than one location, as methods might be defined in different places.

Getting filesystem path of class being executed

The following code snippet will do this for you:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace MyClass with your main class

The resulting File object f represents the .jar file that was executed. You can use this object to get the parent to find the directory that the .jar is in.

How can I return C# class file path

You could use the CallerFilePath attribute:

static void Main(string[] args)
{
Console.WriteLine(GetPath());
Console.Read();
}

static string GetPath([CallerFilePath]string fileName = null)
{
return fileName;
}

How to Find File Path of Class Declaration in a Source Generator

You can use the following code to get the containing file path:

SyntaxNode node = ...;
_ = node.SyntaxTree.FilePath;
_ = node.GetLocation().SourceTree?.FilePath // SourceTree can be null

How to get the path of a running JAR file?

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();

Replace "MyClass" with the name of your class.

Obviously, this will do odd things if your class was loaded from a non-file location.



Related Topics



Leave a reply



Submit