繁体   English   中英

如何控制 Heroku 运行 python 的目录?

[英]How do I control the directory that Heroku runs python in?

我正在尝试在 python 终端中运行 python 脚本,该终端在我部署的 Heroku 应用程序上运行。 该脚本有几个pd.read_csv('~/path_to_csv_file')命令,当我在本地 python 终端中运行脚本时,这些命令按预期工作。 但是,当我尝试使用heroku run python my_script_name在我的 Heroku 应用程序的终端中运行此脚本时,我收到以下错误消息:

FileNotFoundError: [Errno 2] No such file or directory: '/app/path_to_csv_file'

似乎要添加的/app前缀是什么,如何指定正确的路径?

我会尝试在 Python 上使用__file__变量,它可以为您提供脚本的当前位置。

我通常这样使用它:

from os import abspath, dirname

CURRENT_DIRECTORY = dirname(abspath(__file__))

实际上,您的所有代码都部署到了容器中的 /app 文件夹中(您可以在下面看到我在 Heroku 上托管的一个项目的信息部分):

信息部分

如果您真的不想使用__file__ (谁知道),您将需要完全了解 Python 相关文件系统是如何工作的(您首先使用python <file>.py运行的脚本被视为“入口点” ",当前目录)。 然后,您需要在示例中将 CSV 放到一个目录中(确保它至少是您正在上传的应用程序内部的一个目录)并参考您首先运行的脚本:

pd.read_csv('filename') # if the file is in the same directory
pd.read_csv('./path/to/file') # if it's in a directory that is inside the script directory

(会很难用“~”)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM