No such file or directory for relative path

帅比萌擦擦* 提交于 2019-12-14 03:58:14

问题


I have a bottle application in one python file - backend.py. The file contains these definitions:

variable = {
    'field': [f for f in csv.DictReader(open('../data/fields.csv', 'rb'), delimiter=';')]
}

def run_fcgi():
    from bottle import FlupFCGIServer
    run(port=8080, server=FlupFCGIServer)

if __name__ == "__main__":
    run(host='0.0.0.0', port=8087, server='waitress')

When I run this app like:

python backend.py

application is started successfully.

When I run this application as fcgi application (fcgi.py) by supervisor:

#!my_path_to_python

if __name__ == '__main__':
    import backend
    backend.run_fcgi()

I have an error:

Traceback (most recent call last):
  File "path_to_my_project/fcgi.py", line 9, in <module>
    import backend
  File "path_to_my_project/backend.py", line 49, in <module>
    'msk': [i for i in csv.DictReader(open('../data/fields.csv', 'rb'), delimiter=';')],
IOError: [Errno 2] No such file or directory: '../data/fields.csv'

Any ideas?


回答1:


I think It's better not to rely on working directory. and use path relative to file that is uses this path. I mean you can calculate path on the fly:

import os
csv_path = '../data/fields.csv'
csv_path = os.path.join(os.path.dirname(__file__), csv_path)

In this case one be able to run your script on different environment. an full path will be used to be sure that You don't depends on working directory.



来源:https://stackoverflow.com/questions/18934775/no-such-file-or-directory-for-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!