简体   繁体   English

我应该在我的python项目中的哪里放置config.txt

[英]Where should I place a config.txt in my python project

The project folder hierarchy looks like 项目文件夹层次结构看起来像

ProjectName
   ->src
      ->Project.sikuli
          ->myFile.py
          ->config.txt

Now, I have all the settings variables being stores in my config.txt and I'm using ConfigParser to fetch the values from it. 现在,我将所有设置变量存储在config.txt中,并且正在使用ConfigParser从中获取值。 The reason why I'm using this config file here is that, when this sikuli script is moved to another machine for running I can just change the values in it (like paths, username, password) rather than editing the main python script 'myFile.py'. 我在这里使用此配置文件的原因是,当此sikuli脚本移至另一台机器上运行时,我可以更改其中的值(如路径,用户名,密码),而不用编辑主python脚本'myFile .py'。
But the issue I'm encountering now is that I don't want the config file to be placed some where outside the project so that in my script when I try to fetch the values from it, I don't have to mention the absolute path again in the myFile.txt like: 但是我现在遇到的问题是我不希望将配置文件放置在项目外部的某个位置,这样当我尝试从中获取值时,在脚本中不必提及绝对值。再次在myFile.txt中输入路径,例如:

configParser = ConfigParser.RawConfigParser()
configfilePath = r'D:\MyWorkspace\ProjectName\src\Project.sikuli\config.txt'

Instead I want to have the relative path here so that while migrating the project from machine to machine I don't have to do any manipulations in the main script 'myFile.py' 相反,我希望在此处具有相对路径,以便在将项目从计算机迁移到计算机时,不必在主脚本“ myFile.py”中进行任何操作。

So what I'm trying to achieve is like: I should be able to refer the config.txt file by giving it's relative path: 所以我想要达到的目标是:我应该能够通过给出config.txt文件的相对路径来引用它:

configfilePath = r'D:\MyWorkspace\ProjectName\src\Project.sikuli\config.txt'

如果将其与myFile.py保留在同一文件夹中,那么在该Python脚本中,您可以使用以下内容:

configfilePath = os.path.join(os.path.dirname(__file__), 'config.txt')

最佳方法是像在示例中所做的那样,将文件放入 .sikuli捆绑包中,然后按以下方式获取文件的路径:

configFilePath = os.path.join(getBundlePath(), 'config.txt')

I know you can fetch variables and value from a python file by importing it... 我知道您可以通过导入python文件来获取变量和值...

import config

I would put it in the root repertory of the project 我会把它放在项目的根目录中

First, get the path of the currently executed python script: 首先,获取当前执行的python脚本的路径:

myPath = os.path.abspath(os.path.dirname(sys.argv[0]))

and then do a join of myPath and 'config.txt' 然后将myPath和'config.txt'连接起来

configfilePath = os.path.join(myPath, 'config.txt')

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

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