简体   繁体   English

Python无法使用Powershell找到路径

[英]Python can't find path with Powershell

I have a rather unusual problem. 我有一个不寻常的问题。 I wrote a python script which needs API keys. 我写了一个需要API密钥的python脚本。 Since I don't want them floating around on the internet I created a seperate .json with the keys and added it to .gitignore. 由于我不想让他们在互联网上四处徘徊,因此我创建了带有密钥的单独的.json并将其添加到.gitignore中。 So far so good. 到现在为止还挺好。

I wrote the program with VSCode and there I could execute it no problem. 我用VSCode编写了程序,在那里我可以执行它。 But when I try to use my program with the normal PowerShell it simply won't work. 但是,当我尝试将程序与普通的PowerShell一起使用时,它根本无法工作。 I get this error message when I run it on the external PS: FileNotFoundError: [Errno 2] No such file or directory: './master-folder/key.json' 我在外部PS上运行该错误消息: FileNotFoundError: [Errno 2] No such file or directory: './master-folder/key.json'

I use a virtualenv, for the packages but that shouldn't affect anything (of course I activated it in PS). 我对软件包使用了virtualenv,但这不会影响任何东西(当然我在PS中将其激活了)。 Here's the part of the code once again: 这再次是代码的一部分:

keys_fp = './master-folder/key.json'

keys = load(open(keys_fp, 'r'))

The folder structure is as follows: 文件夹结构如下:

.
├── programs
│   └── program.py
└── key.json

Based on your comments, your working directory is 根据您的评论,您的工作目录为

E:\Git\master-folder\programs\

and inside your script, you're referencing 在脚本中,您引用的是

./master-folder/key.json

which resolves to 解析为

E:\Git\master-folder\programs\master-folder\key.json

but that doesn't exist. 但这不存在。 If you adjust your script to use the proper path, it should resolve your problem: 如果您调整脚本以使用正确的路径,它将解决您的问题:

keys_fp = f'{os.getcwd()}\\..\\key.json'

According to this answer , you can access the script's root with the following: 根据此答案 ,您可以使用以下命令访问脚本的根目录:

import os
root = os.path.dirname(os.path.realpath(__file__))
keys_fp = f'{root}\\..\\key.json'

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

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