hsestupin
hsestupin

Reputation: 1115

Determine file-script directory at runtime from clojure

I am creating a third-party library for Clojure. In the core of this library I need to run script from the operation system. In this case I cannot use absolute path to this file like this /Users/me/src/clojure-pymorphy/src/pymorphy/pymorphy.py.

But if I use relative path script/script.py - than sometimes location of the script could be determined as wrong. It depends on the directory from which I run/use this clojure library. Because this library will be distributed as the third-party I need the way to determine the path of script.py from Clojure source code.

Project folders looks like this:

clojure-pymorphy/
    src/
        pymorphy/
            pymorphy.py
        pymorphy.clj

Script pymorphy.py is invoked from pymorphy.clj. File pymorphy.clj begins from this lines:

(ns pymorphy
  (:import  (java.util ArrayList)
            (jep Jep)))

I've tried to find out is there a way to determine directory to pymorphy namespace at runtime and just simply add "pymorphy/pymorphy.py" to it. But after many hours of googling I come to conclusion that it's not possible.

So is there any other ways to dynamically determine path to clojure namespace at runtime?

Many thanks.

Upvotes: 0

Views: 264

Answers (2)

Alex Ott
Alex Ott

Reputation: 87164

If you to run this script, so this will be something like - this will copy script to temp file, and run it. You need to create file, because if you'll pack everything into jar, then interpreter won't be able to read file..

(let [tmp (File/createTempFile "tmp" "py")
      script (clojure.java.io/resource "pymorphy/pymorphy.py")]
  (try
    (when (and script (.exists tmp))
      (with-open [os (.openStream script)]
        (clojure.java.io/copy os tmp))
      (run-script....))
    (finally
      (when (.exists tmp)
        (.delete tmp)))))

Upvotes: 1

hsestupin
hsestupin

Reputation: 1115

While looking at the similar questions at stackoverflow I find the solution:

(.getFile (clojure.java.io/resource "pymorphy/pymorphy.py"))

Upvotes: 2

Related Questions