Pycharm:为运行管理设置环境变量。py任务

时间:2021-01-15 01:01:33

I have moved my SECRET_KEY value out of my settings file, and it gets set when I load my virtualenv. I can confirm the value is present from python manage.py shell.

我已经将我的SECRET_KEY值从设置文件中移除,当我加载我的virtualenv时,它将被设置。我可以确认值来自python管理。py壳。

When I run the Django Console, SECRET_KEY is missing, as it should. So in preferences, I go to Console>Django Console and load SECRET_KEY and the appropriate value. I go back into the Django Console, and SECRET_KEY is there.

当我运行Django控制台时,会丢失SECRET_KEY,这是应该的。因此,在首选项中,我转到控制台>Django控制台并加载SECRET_KEY和相应的值。我回到Django控制台,并在那里使用了SECRET_KEY。

As expected, I cannot yet run a manage.py Task because it has yet to find the SECRET_KEY. So I go into Run>Edit Configurations to add SECRET_KEY into Django server and Django Tests, and into the project server. Restart Pycharm, confirm keys.

正如所料,我还不能管理。py任务,因为它还没有找到SECRET_KEY。因此,我开始运行>编辑配置,将SECRET_KEY添加到Django服务器和Django测试中,并添加到项目服务器中。重启Pycharm,确认键。

When I run a manage.py Task, such as runserver, I still get KeyError: 'SECRET_KEY'.

当我管理的时候。py任务,比如runserver,我仍然会得到KeyError:“SECRET_KEY”。

Where do I put this key?

我把钥匙放在哪里?

11 个解决方案

#1


40  

Because Pycharm is not launching from a terminal, your environment will not be loaded. In short, any GUI program will not inherit the SHELL variables. See this for reasons (assuming a Mac).

因为Pycharm不是从终端启动的,所以你的环境不会被载入。简而言之,任何GUI程序都不会继承SHELL变量。这是有原因的(假设是Mac)。

However, there are several basic solutions to this problem. As @user3228589 posted, you can set this up as a variable within PyCharm. This has several pros and cons. I personally don't like this approach because it's not a single source. To fix this, I use a small function at the top of my settings.py file which looks up the variable inside a local .env file. I put all of my "private" stuff in there. I also can reference this in my virtualenv.

然而,这个问题有几个基本的解决方法。作为@user3228589,您可以将其设置为PyCharm中的变量。这有几个优点和缺点。我个人不喜欢这种方法,因为它不是单一来源。为了解决这个问题,我在设置的顶部使用了一个小函数。py文件,它在本地.env文件中查找变量。我把我所有的“私人”东西都放进去了。我也可以在我的virtualenv中引用它。

Here is what it looks like.

这是它的样子。

-- settings.py

——settings.py

def get_env_variable(var_name, default=False):
    """
    Get the environment variable or return exception
    :param var_name: Environment Variable to lookup
    """
    try:
        return os.environ[var_name]
    except KeyError:
        import StringIO
        import ConfigParser
        env_file = os.environ.get('PROJECT_ENV_FILE', SITE_ROOT + "/.env")
        try:
            config = StringIO.StringIO()
            config.write("[DATA]\n")
            config.write(open(env_file).read())
            config.seek(0, os.SEEK_SET)
            cp = ConfigParser.ConfigParser()
            cp.readfp(config)
            value = dict(cp.items('DATA'))[var_name.lower()]
            if value.startswith('"') and value.endswith('"'):
                value = value[1:-1]
            elif value.startswith("'") and value.endswith("'"):
                value = value[1:-1]
            os.environ.setdefault(var_name, value)
            return value
        except (KeyError, IOError):
            if default is not False:
                return default
            from django.core.exceptions import ImproperlyConfigured
            error_msg = "Either set the env variable '{var}' or place it in your " \
                        "{env_file} file as '{var} = VALUE'"
            raise ImproperlyConfigured(error_msg.format(var=var_name, env_file=env_file))

# Make this unique, and don't share it with anybody.
SECRET_KEY = get_env_variable('SECRET_KEY')

Then the env file looks like this:

那么env文件如下:

#!/bin/sh
#
# This should normally be placed in the ${SITE_ROOT}/.env
#
# DEPLOYMENT DO NOT MODIFY THESE..
SECRET_KEY='XXXSECRETKEY'

And finally your virtualenv/bin/postactivate can source this file. You could go further and export the variables as described here if you'd like, but since settings file directly calls the .env, there isn't really a need.

最后,您的virtualenv/bin/postactivate可以提供这个文件的源代码。如果愿意,您可以进一步导出这里描述的变量,但是由于设置文件直接调用.env,所以实际上不需要。

#2


19  

To set your environment variables in PyCharm do the following:

要在PyCharm中设置你的环境变量,请做以下事情:

  • Open the 'File' menu
  • 打开“文件”菜单
  • Click 'Settings'
  • 点击“设置”
  • Click the '+' sign next to 'Console'
  • 单击“控制台”旁边的“+”符号
  • Click Python Console
  • 单击Python控制台
  • Click the '...' button next to environment variables
  • 点击“…'按钮旁边的环境变量
  • Click the '+' to add environment variables
  • 单击“+”添加环境变量

#3


12  

Same here, for some reason PyCharm cant see exported env vars. For now i set SECRET_KEY in PyCharm Run/Debug Configurations -> "Environment variables"

这里也一样,出于某种原因,PyCharm看不到出口的env vars。现在,我在PyCharm运行/调试配置中设置了SECRET_KEY—>“环境变量”

#4


8  

You can set the manage.py task environment variables via:

您可以设置管理。py任务环境变量:

Preferences| Languages&Frameworks| Django| Manage.py tasks

Django偏好|语言和框架| |管理。py任务

Setting the env vars via the run/debug/console configuration won't affect the built in pycharm's manage.py task.

通过运行/调试/控制台配置设置env vars不会影响pycharm中的内置管理。py任务。

#5


8  

Another option that's worked for me:

另一个对我有用的选择:

  1. Open a terminal
  2. 打开一个终端
  3. Activate the virtualenv of the project which will cause the hooks to run and set the environment variables
  4. 激活项目的virtualenv,它将导致钩子运行并设置环境变量
  5. Launch PyCharm from this command line.
  6. 从这个命令行启动PyCharm。

Pycharm will then have access to the environment variables. Likely because of something having to do with the PyCharm process being a child of the shell.

Pycharm可以访问环境变量。很可能是由于PyCharm过程是shell的产物。

#6


5  

In Pycharm manage.py tasks run in an isolated process that do not have access to your environment variables (not the same as Run/Debug).

在Pycharm管理。py任务在一个独立的进程中运行,该进程不具有对环境变量的访问权限(与运行/调试不同)。

The simplest solution is to make your python code aware of environment variables by reading them from your .env file directly.

最简单的解决方案是通过直接从.env文件中读取环境变量,使python代码了解环境变量。

Take a look at: https://github.com/joke2k/django-environ

看一看:https://github.com/joke2k/django- environment。

import environ

env = environ.Env.read_env() # reading .env file

SECRET_KEY = env('SECRET_KEY')

That way you have a single source of configurations, and less settings in the IDE.

这样,您就有了一个配置源,并且IDE中的设置更少。

Hope that helps,

希望有所帮助,

#7


2  

To paraphrase @antero-ortiz's answer, instead of using the default Mac double-click or spotlight search to launch PyCharm, you can launch it directly from the terminal. This will inherit all of your environment variables from your terminal session to the PyCharm app.

套用@antero-ortiz的回答,不用默认的Mac双击或spotlight搜索来启动PyCharm,你可以直接从终端启动。这将从您的终端会话到PyCharm应用程序继承所有环境变量。

Here's how I solve this issue.

下面是我如何解决这个问题。

  1. From your terminal program, run the snippet below.
  2. 从终端程序运行下面的代码片段。
  3. Validate that things worked by following the instructions to Edit your Run/Debug Configurations and,
    1. Clicking the ... next to Environment variables
    2. 单击……旁边的环境变量
    3. Then clicking Show at the bottom right of the screen that pops up. This will show all of the environment variables inherited by the Debug process.
    4. 然后单击弹出的屏幕右下角的Show。这将显示调试过程继承的所有环境变量。
    5. Find your SECRET_KEY in this list. If it's not there, post a comment on this answer and we can try to figure it out!
    6. 在这个列表中找到您的SECRET_KEY。如果它不在那里,贴一个关于这个答案的评论,我们可以试着找出它!
  4. 验证通过以下指令编辑您的运行/调试配置,并单击…在环境变量旁边,单击弹出的屏幕右下角的Show。这将显示调试过程继承的所有环境变量。在这个列表中找到您的SECRET_KEY。如果它不在那里,贴一个关于这个答案的评论,我们可以试着找出它!
  5. You'll likely need to launch PyCharm this way every time you start it.
  6. 每次启动时,您可能都需要以这种方式启动PyCharm。

Snippet:

代码片段:

# This file would presumably export SECRET_KEY
source /path/to/env/file
# This is just a shortcut to finding out where you installed PyCharm
# If you used brew cask, it's probably in /opt/homebrew-cask/Caskroom/pycharm
open $(locate PyCharm.app | egrep 'PyCharm.app$')

Side note

Including environment variables in a file that is then source'd is a common pattern for Django development, and the discussion of that best practice is best left out of answers.

在一个文件中包含环境变量是Django开发的一个常见模式,而关于这个最佳实践的讨论最好不要给出答案。

#8


0  

based on @rh0dium amazing answer i've made this class:

基于@rh0dium惊人的回答,我做了这堂课:

here's my settings.py:

这是我的settings.py:

import os


class EnvironmentSettings():
    """Access to environment variables via system os or .env file for development

    """
    def __init__(self, root_folder_path):
        self._root_folder_path = root_folder_path

    def __getitem__(self, key):
        return self._get_env_variable(key)

    def __setitem__(self, key, value):
        raise InvalidOperationException('Environment Settings are read-only')

    def __delitem__(self, key):
        raise InvalidOperationException('Environment Settings are read-only')

    def _get_env_variable(self, var_name, default=False):
        """
        Get the environment variable or return exception
        :param var_name: Environment Variable to lookup
        """
        try:
            return os.environ[var_name]
        except KeyError:
            from io import StringIO
            from configparser import ConfigParser

            env_file = os.environ.get('PROJECT_ENV_FILE', self._root_folder_path + "/.env")
            try:
                config = StringIO()
                config.write("[DATA]\n")
                config.write(open(env_file).read())
                config.seek(0, os.SEEK_SET)
                cp = ConfigParser()
                cp.readfp(config)
                value = dict(cp.items('DATA'))[var_name.lower()]
                if value.startswith('"') and value.endswith('"'):
                    value = value[1:-1]
                elif value.startswith("'") and value.endswith("'"):
                    value = value[1:-1]
                os.environ.setdefault(var_name, value)
                return value
            except (KeyError, IOError):
                if default is not False:
                    return default
                error_msg = "Either set the env variable '{var}' or place it in your " \
                            "{env_file} file as '{var} = VALUE'"
                raise ConfigurationError(error_msg.format(var=var_name, env_file=env_file))


class ConfigurationError(Exception):
    pass


class InvalidOperationException(Exception):
    pass

and inside my runserver.py i have this calling code:

runserver里面。py我有这个调用代码:

from settings import EnvironmentSettings

root_folder_path = os.path.dirname(os.path.abspath(__file__))
env_settings = EnvironmentSettings(root_folder_path)
config_name = env_settings['APP_SETTINGS']

#9


0  

The answer by @(nu everest) did not work for me. Whatever you described in the question worked for me. You can set all environment variables in the Run/Debug Configurations dialog. This is w.r.t PyCharm 2016.1 and also as per https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-python.html?origin=old_help

@(如珠穆朗玛峰)的答案对我不起作用。你在问题中所描述的一切都对我起了作用。您可以在运行/调试配置对话框中设置所有环境变量。这是w.r。tpycharm 2016.1,也有https://www.jetbrains.com/help/pycharm/2016.1/run-debug- python.html?来源:old_help

#10


0  

I'm trying this setup currently. I have an env.local file in my project root. My manage.py looks like this:

我目前正在尝试这个设置。我有一个env。本地文件在我的项目根。我的管理。py是这样的:

#!/usr/bin/env python
import os
import sys


if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")

    # Load environment variables from env.local, if option --load-env specified.
    # Good for injecting environment into PyCharm run configurations for example and no need to
    # manually load the env values for manage.py commands
    if "--load-env" in sys.argv:
        with open("env.local") as envfile:
            for line in envfile:
                if line.strip():
                    setting = line.strip().split("=", maxsplit=1)
                    os.environ.setdefault(setting[0], setting[1])
        sys.argv.remove("--load-env")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Then I just pass --load-env in the PyCharm run dialog and all the environment variables will be loaded in for the time of the run.

然后在PyCharm运行对话框中传递-load-env,运行时所有的环境变量都会被加载进来。

#11


0  

Please note that the answer mentioned by "nu everest" works but you will not see Console tab available unless you create a project in pycharm. As individual files can be run without creating a project in pycharm some people might be confused. Although you have also to note that settings are lost to run-configurations that do not belong to a project when pycharm is closed.

请注意,“nu everest”所提到的答案是有效的,但是您将看不到控制台选项卡,除非您使用pycharm创建一个项目。由于可以在pycharm中运行单个文件而不创建项目,一些人可能会感到困惑。尽管您还需要注意,当pycharm关闭时,设置会丢失到不属于某个项目的运行配置中。

#1


40  

Because Pycharm is not launching from a terminal, your environment will not be loaded. In short, any GUI program will not inherit the SHELL variables. See this for reasons (assuming a Mac).

因为Pycharm不是从终端启动的,所以你的环境不会被载入。简而言之,任何GUI程序都不会继承SHELL变量。这是有原因的(假设是Mac)。

However, there are several basic solutions to this problem. As @user3228589 posted, you can set this up as a variable within PyCharm. This has several pros and cons. I personally don't like this approach because it's not a single source. To fix this, I use a small function at the top of my settings.py file which looks up the variable inside a local .env file. I put all of my "private" stuff in there. I also can reference this in my virtualenv.

然而,这个问题有几个基本的解决方法。作为@user3228589,您可以将其设置为PyCharm中的变量。这有几个优点和缺点。我个人不喜欢这种方法,因为它不是单一来源。为了解决这个问题,我在设置的顶部使用了一个小函数。py文件,它在本地.env文件中查找变量。我把我所有的“私人”东西都放进去了。我也可以在我的virtualenv中引用它。

Here is what it looks like.

这是它的样子。

-- settings.py

——settings.py

def get_env_variable(var_name, default=False):
    """
    Get the environment variable or return exception
    :param var_name: Environment Variable to lookup
    """
    try:
        return os.environ[var_name]
    except KeyError:
        import StringIO
        import ConfigParser
        env_file = os.environ.get('PROJECT_ENV_FILE', SITE_ROOT + "/.env")
        try:
            config = StringIO.StringIO()
            config.write("[DATA]\n")
            config.write(open(env_file).read())
            config.seek(0, os.SEEK_SET)
            cp = ConfigParser.ConfigParser()
            cp.readfp(config)
            value = dict(cp.items('DATA'))[var_name.lower()]
            if value.startswith('"') and value.endswith('"'):
                value = value[1:-1]
            elif value.startswith("'") and value.endswith("'"):
                value = value[1:-1]
            os.environ.setdefault(var_name, value)
            return value
        except (KeyError, IOError):
            if default is not False:
                return default
            from django.core.exceptions import ImproperlyConfigured
            error_msg = "Either set the env variable '{var}' or place it in your " \
                        "{env_file} file as '{var} = VALUE'"
            raise ImproperlyConfigured(error_msg.format(var=var_name, env_file=env_file))

# Make this unique, and don't share it with anybody.
SECRET_KEY = get_env_variable('SECRET_KEY')

Then the env file looks like this:

那么env文件如下:

#!/bin/sh
#
# This should normally be placed in the ${SITE_ROOT}/.env
#
# DEPLOYMENT DO NOT MODIFY THESE..
SECRET_KEY='XXXSECRETKEY'

And finally your virtualenv/bin/postactivate can source this file. You could go further and export the variables as described here if you'd like, but since settings file directly calls the .env, there isn't really a need.

最后,您的virtualenv/bin/postactivate可以提供这个文件的源代码。如果愿意,您可以进一步导出这里描述的变量,但是由于设置文件直接调用.env,所以实际上不需要。

#2


19  

To set your environment variables in PyCharm do the following:

要在PyCharm中设置你的环境变量,请做以下事情:

  • Open the 'File' menu
  • 打开“文件”菜单
  • Click 'Settings'
  • 点击“设置”
  • Click the '+' sign next to 'Console'
  • 单击“控制台”旁边的“+”符号
  • Click Python Console
  • 单击Python控制台
  • Click the '...' button next to environment variables
  • 点击“…'按钮旁边的环境变量
  • Click the '+' to add environment variables
  • 单击“+”添加环境变量

#3


12  

Same here, for some reason PyCharm cant see exported env vars. For now i set SECRET_KEY in PyCharm Run/Debug Configurations -> "Environment variables"

这里也一样,出于某种原因,PyCharm看不到出口的env vars。现在,我在PyCharm运行/调试配置中设置了SECRET_KEY—>“环境变量”

#4


8  

You can set the manage.py task environment variables via:

您可以设置管理。py任务环境变量:

Preferences| Languages&Frameworks| Django| Manage.py tasks

Django偏好|语言和框架| |管理。py任务

Setting the env vars via the run/debug/console configuration won't affect the built in pycharm's manage.py task.

通过运行/调试/控制台配置设置env vars不会影响pycharm中的内置管理。py任务。

#5


8  

Another option that's worked for me:

另一个对我有用的选择:

  1. Open a terminal
  2. 打开一个终端
  3. Activate the virtualenv of the project which will cause the hooks to run and set the environment variables
  4. 激活项目的virtualenv,它将导致钩子运行并设置环境变量
  5. Launch PyCharm from this command line.
  6. 从这个命令行启动PyCharm。

Pycharm will then have access to the environment variables. Likely because of something having to do with the PyCharm process being a child of the shell.

Pycharm可以访问环境变量。很可能是由于PyCharm过程是shell的产物。

#6


5  

In Pycharm manage.py tasks run in an isolated process that do not have access to your environment variables (not the same as Run/Debug).

在Pycharm管理。py任务在一个独立的进程中运行,该进程不具有对环境变量的访问权限(与运行/调试不同)。

The simplest solution is to make your python code aware of environment variables by reading them from your .env file directly.

最简单的解决方案是通过直接从.env文件中读取环境变量,使python代码了解环境变量。

Take a look at: https://github.com/joke2k/django-environ

看一看:https://github.com/joke2k/django- environment。

import environ

env = environ.Env.read_env() # reading .env file

SECRET_KEY = env('SECRET_KEY')

That way you have a single source of configurations, and less settings in the IDE.

这样,您就有了一个配置源,并且IDE中的设置更少。

Hope that helps,

希望有所帮助,

#7


2  

To paraphrase @antero-ortiz's answer, instead of using the default Mac double-click or spotlight search to launch PyCharm, you can launch it directly from the terminal. This will inherit all of your environment variables from your terminal session to the PyCharm app.

套用@antero-ortiz的回答,不用默认的Mac双击或spotlight搜索来启动PyCharm,你可以直接从终端启动。这将从您的终端会话到PyCharm应用程序继承所有环境变量。

Here's how I solve this issue.

下面是我如何解决这个问题。

  1. From your terminal program, run the snippet below.
  2. 从终端程序运行下面的代码片段。
  3. Validate that things worked by following the instructions to Edit your Run/Debug Configurations and,
    1. Clicking the ... next to Environment variables
    2. 单击……旁边的环境变量
    3. Then clicking Show at the bottom right of the screen that pops up. This will show all of the environment variables inherited by the Debug process.
    4. 然后单击弹出的屏幕右下角的Show。这将显示调试过程继承的所有环境变量。
    5. Find your SECRET_KEY in this list. If it's not there, post a comment on this answer and we can try to figure it out!
    6. 在这个列表中找到您的SECRET_KEY。如果它不在那里,贴一个关于这个答案的评论,我们可以试着找出它!
  4. 验证通过以下指令编辑您的运行/调试配置,并单击…在环境变量旁边,单击弹出的屏幕右下角的Show。这将显示调试过程继承的所有环境变量。在这个列表中找到您的SECRET_KEY。如果它不在那里,贴一个关于这个答案的评论,我们可以试着找出它!
  5. You'll likely need to launch PyCharm this way every time you start it.
  6. 每次启动时,您可能都需要以这种方式启动PyCharm。

Snippet:

代码片段:

# This file would presumably export SECRET_KEY
source /path/to/env/file
# This is just a shortcut to finding out where you installed PyCharm
# If you used brew cask, it's probably in /opt/homebrew-cask/Caskroom/pycharm
open $(locate PyCharm.app | egrep 'PyCharm.app$')

Side note

Including environment variables in a file that is then source'd is a common pattern for Django development, and the discussion of that best practice is best left out of answers.

在一个文件中包含环境变量是Django开发的一个常见模式,而关于这个最佳实践的讨论最好不要给出答案。

#8


0  

based on @rh0dium amazing answer i've made this class:

基于@rh0dium惊人的回答,我做了这堂课:

here's my settings.py:

这是我的settings.py:

import os


class EnvironmentSettings():
    """Access to environment variables via system os or .env file for development

    """
    def __init__(self, root_folder_path):
        self._root_folder_path = root_folder_path

    def __getitem__(self, key):
        return self._get_env_variable(key)

    def __setitem__(self, key, value):
        raise InvalidOperationException('Environment Settings are read-only')

    def __delitem__(self, key):
        raise InvalidOperationException('Environment Settings are read-only')

    def _get_env_variable(self, var_name, default=False):
        """
        Get the environment variable or return exception
        :param var_name: Environment Variable to lookup
        """
        try:
            return os.environ[var_name]
        except KeyError:
            from io import StringIO
            from configparser import ConfigParser

            env_file = os.environ.get('PROJECT_ENV_FILE', self._root_folder_path + "/.env")
            try:
                config = StringIO()
                config.write("[DATA]\n")
                config.write(open(env_file).read())
                config.seek(0, os.SEEK_SET)
                cp = ConfigParser()
                cp.readfp(config)
                value = dict(cp.items('DATA'))[var_name.lower()]
                if value.startswith('"') and value.endswith('"'):
                    value = value[1:-1]
                elif value.startswith("'") and value.endswith("'"):
                    value = value[1:-1]
                os.environ.setdefault(var_name, value)
                return value
            except (KeyError, IOError):
                if default is not False:
                    return default
                error_msg = "Either set the env variable '{var}' or place it in your " \
                            "{env_file} file as '{var} = VALUE'"
                raise ConfigurationError(error_msg.format(var=var_name, env_file=env_file))


class ConfigurationError(Exception):
    pass


class InvalidOperationException(Exception):
    pass

and inside my runserver.py i have this calling code:

runserver里面。py我有这个调用代码:

from settings import EnvironmentSettings

root_folder_path = os.path.dirname(os.path.abspath(__file__))
env_settings = EnvironmentSettings(root_folder_path)
config_name = env_settings['APP_SETTINGS']

#9


0  

The answer by @(nu everest) did not work for me. Whatever you described in the question worked for me. You can set all environment variables in the Run/Debug Configurations dialog. This is w.r.t PyCharm 2016.1 and also as per https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-python.html?origin=old_help

@(如珠穆朗玛峰)的答案对我不起作用。你在问题中所描述的一切都对我起了作用。您可以在运行/调试配置对话框中设置所有环境变量。这是w.r。tpycharm 2016.1,也有https://www.jetbrains.com/help/pycharm/2016.1/run-debug- python.html?来源:old_help

#10


0  

I'm trying this setup currently. I have an env.local file in my project root. My manage.py looks like this:

我目前正在尝试这个设置。我有一个env。本地文件在我的项目根。我的管理。py是这样的:

#!/usr/bin/env python
import os
import sys


if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")

    # Load environment variables from env.local, if option --load-env specified.
    # Good for injecting environment into PyCharm run configurations for example and no need to
    # manually load the env values for manage.py commands
    if "--load-env" in sys.argv:
        with open("env.local") as envfile:
            for line in envfile:
                if line.strip():
                    setting = line.strip().split("=", maxsplit=1)
                    os.environ.setdefault(setting[0], setting[1])
        sys.argv.remove("--load-env")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Then I just pass --load-env in the PyCharm run dialog and all the environment variables will be loaded in for the time of the run.

然后在PyCharm运行对话框中传递-load-env,运行时所有的环境变量都会被加载进来。

#11


0  

Please note that the answer mentioned by "nu everest" works but you will not see Console tab available unless you create a project in pycharm. As individual files can be run without creating a project in pycharm some people might be confused. Although you have also to note that settings are lost to run-configurations that do not belong to a project when pycharm is closed.

请注意,“nu everest”所提到的答案是有效的,但是您将看不到控制台选项卡,除非您使用pycharm创建一个项目。由于可以在pycharm中运行单个文件而不创建项目,一些人可能会感到困惑。尽管您还需要注意,当pycharm关闭时,设置会丢失到不属于某个项目的运行配置中。