ideonate / cdsdashboards

JupyterHub extension for ContainDS Dashboards
https://cdsdashboards.readthedocs.io/
Other
200 stars 38 forks source link

How to use relative path #57

Closed pbl357 closed 3 years ago

pbl357 commented 3 years ago

I want to use relative path in my streamlit demo, e.g f = open('abc.log') but it not works, I must use it like this, the absolute path f = open('/home/user/{username}/{streamlit}/abc.log') so how should i do

danlester commented 3 years ago

Thank you for your question. You need to first find out the location of your Python script, and then calculate the relative path from there (or you could change the working folder to that same location).

Something like this, assuming your file is in the same folder as your Python script:

import os

HERE = os.path.dirname(__file__)
f = open(os.path.join(HERE, 'abc.log'), 'r')

Or just use 'folder/abc.log' or similar if not in exactly the same folder.

pbl357 commented 3 years ago

Thank you for your answer, I may not describe it clearly enough. if i run the script in the jupyterlab, it`s ok, but i run it through containDS, it not very well, because the relative path

i think the containDS run the script by using absolute path python3 -m voila /home/user/{username}/./my.ipynb or /usr/bin/python3 /usr/local/bin/streamlit run /home/user/{username}/./intro.py so in my script, I can only use absolute path

danlester commented 3 years ago

My code snippet above was exactly that - a way to find out the absolute path to use.

Maybe taking a look at the values of the variables would help you understand what I'm trying to suggest:

HERE = os.path.dirname(__file__)
print(HERE)  # or st.write(HERE) etc
print(os.path.join(HERE, 'abc.log'))

If you still think I've misunderstood, maybe a more complete example would help (including an explanation of the folder structure for your files). I'm not too sure why you've written {username}/{streamlit} above - whether they are appearing exactly like that, or whether you are using them here instead of revealing your exact username.

pbl357 commented 3 years ago

Apologize for my late,i got your suggestion and will check my code, {username}/{streamlit} are placeholder