atom-community / atom-script

:runner: Run ( scripts | selections | source ) in Atom
https://atom.io/packages/script
MIT License
735 stars 269 forks source link

Relative path referencing error #223

Open mlefleur opened 9 years ago

mlefleur commented 9 years ago

I'm having this problem with Python (I havn't tried this with different languages). When referring to another file inside the source and running the script, there is an error where the file cannot be found. It seems to be that the program is looking for the file in relation to the base directory you are working from in Atom rather than in relation to the location of the source file.

e.g. We have:

Inside main.py we want to load an image, so you would think that we could refer to the image as "..\img\image.png". But because we are in the base directory in Atom, this causes an error. This isn't due to an error in the code from the Python script.

Ways around problem:

erran commented 9 years ago

@MykonBlu Is this with or without using the Current Working Directory option? Setting this option will set the cwd before running your script.

erran commented 9 years ago

This isn't due to an error in the code from the Python script.

@MykonBlu While I don't think this is an error per say, I think it could very well be a base path problem.

In Ruby I know one common idiom to ensure the path is not relative is to expand the path using the current file.

relative_path = '../../my_file.txt'

# This throws an error if you're not in the base directory
File.open(relative_path)

# NOTE: `__FILE__` refers to the absolute path to the current file
absolute_path = File.expand_path('../../Gemfile', __FILE__)

# This will always pass
File.open(absolute_path)
erran commented 9 years ago

via @caleb531:

I just wanted to let you know that I discovered a simple and straightforward way to ensure correct file paths within my existing Python scripts:

import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
FabianInostroza commented 8 years ago

Where is the "Current Working Directory" option?

yafengguo commented 6 years ago

This is actually related to how ATOM get current working directory for python script. A quick solution is, don't open atom from launch pad or dock, but open it from shell, from where your project/directory located.