2

I am having trouble referencing a file in another directory in my rails app. I have a controller located in my_app/app/controllers/concerns/my_controller with the following line of code:

@value = %x(python ../../lib/assets/python/test.py #{Shellwords.escape(params[:first_name])} 2>&1)

That is running test.py located in my_app/lib/assets/python/test.py with the %x() subshell.

When I reference the file from my desktop, it runs the test.py code correctly. But when I place the script in my lib/assets/python folder I get a cannot find file or directory error.

How should I correctly reference my test.py file so that the %x() command can find it?

1
  • What is the environment of the user running the %x(...)? Commented May 5, 2015 at 0:32

1 Answer 1

1

If the PATH isn't set so the user running your code is able to find python then you'll get that error.

Instead of referencing it as python which forces the system to try to locate Python by walking the PATH, use the full path to the interpreter. You can usually find that by typing

which python

at the command prompt, and then putting that into the code replacing the single word python.


Ruby's File class has several very useful methods for finding the path from a directory to another, or to a specific file. Look at:

I generally use realpath since it checks to see that the target actually exists before returning a path to it.

You could use it something like:

File.realpath('../../path/to/file', File.dirname(__FILE__))

which should return a path relative to the script that is currently being executed.

You can reference from the running script using:

File.realpath('../../path/to/file', File.dirname($0))

You'll need to figure out whether you want to base your path from __FILE__ or $0 and what the differences are.

Sign up to request clarification or add additional context in comments.

3 Comments

that works when I use the full file path to the test.py file, but how can I reference the file from within the app. /Users/me/anaconda/bin/python /Users/me/workspace/my_app/lib/assets/python/test.py works but, when I reference the file from within the app I get /Users/me/anaconda/bin/python: can't open file '../../lib/assets/python/test.py': [Errno 2] No such file or directory
See the updated information about using File's methods.
I tried pretty much every combo I could think of and finally realized why it wasn't working, I needed to escape the File.realpath command. @value = %x(/Users/me/anaconda/bin/python #{Shellwords.escape(File.absolute_path('lib/assets/python/test.py'))})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.