未验证 提交 bfc869ae 编写于 作者: F Frost Ming

Activate PEP 582 by writing env var into WinReg

Close #191
上级 bf3fb38b
......@@ -108,7 +108,7 @@ if __name__ == '__main__':
app.run()
```
Set environment variable `eval $(pdm --pep582)`. Now you can run the app directly with your familiar **Python interpreter**:
If you are a Bash user, set the environment variable by `eval $(pdm --pep582)`. Now you can run the app directly with your familiar **Python interpreter**:
```bash
$ python /home/frostming/workspace/flask_app/app.py
......@@ -119,7 +119,7 @@ $ python /home/frostming/workspace/flask_app/app.py
Ta-da! You are running an app with its dependencies installed in an isolated place, while no virtualenv is involved.
You can also preserve the setting by appending the output of `pdm --pep582` to the end of `.bash_profile`.
For Windows users, please refer to [the doc](https://pdm.fming.dev/#enable-pep-582-globally) about how to make it work.
If you are curious about how this works, check [this doc section](https://pdm.fming.dev/project/#how-we-make-pep-582-packages-available-to-the-python-interpreter) for some explanation.
......
......@@ -103,7 +103,7 @@ if __name__ == '__main__':
app.run()
```
设置环境变量`eval $(pdm --pep582)`,现在你可以用你最熟悉的 **Python 解释器** 运行脚本
如果你使用的是 Bash,可以通过执行`eval $(pdm --pep582)`设置环境变量,现在你可以用你最熟悉的 **Python 解释器** 运行脚本了
```bash
$ python /home/frostming/workspace/flask_app/app.py
......@@ -113,7 +113,8 @@ $ python /home/frostming/workspace/flask_app/app.py
```
当当当当!你已经把应用运行起来了,而它的依赖全被安装在一个项目独立的文件夹下,而我们完全没有创建虚拟环境。
你如果希望自动启用此特性,将`pdm --pep582`的输出贴到你的`.bash_profile`后面即可。
如果你是 Windows 用户,请参考[文档](https://pdm.fming.dev/#enable-pep-582-globally)获取设置的方法。
如果你好奇这是如何实现的,可以查看[文档](https://pdm.fming.dev/project/#how-we-make-pep-582-packages-available-to-the-python-interpreter),有一个简短的解释。
......
......@@ -47,7 +47,16 @@ $ pip install --user pdm
### Enable PEP 582 globally
To make the Python interpreters aware of PEP 582 packages, one need to add the `pdm/pep582/sitecustomize.py`
to the Python library search path. The command can be produced by `pdm --pep582 [<SHELL>]` and if `<SHELL>`
to the Python library search path.
#### For Windows users
One just needs to execute `pdm --pep582`, then environment variable will be changed automatically. Don't forget
to restart the terminal session to take effect.
#### For Mac and Linux users
The command to change the environment variables can be produced by `pdm --pep582 [<SHELL>]`. If `<SHELL>`
isn't given, PDM will pick one based on some guesses.
You may want to write a line in your `.bash_profile`(or similar profiles) to make it effective when login.
......@@ -57,6 +66,8 @@ For example, in bash you can do this:
$ pdm --pep582 >> ~/.bash_profile
```
Once again, Don't forget to restart the terminal session to take effect.
**This setup may become the default in the future.**
### Use the docker image
......
For Windows users, `pdm --pep582` can enable PEP 582 globally by manipulating the WinReg.
......@@ -14,6 +14,7 @@ from pdm.cli.utils import (
format_lockfile,
format_toml,
save_version_specifiers,
set_env_in_reg,
)
from pdm.exceptions import NoPythonVersion, PdmUsageError, ProjectError
from pdm.formats import FORMATS
......@@ -540,18 +541,17 @@ def print_pep582_command(shell: str = "AUTO"):
"""Print the export PYTHONPATH line to be evaluated by the shell."""
import shellingham
if os.name == "nt":
set_env_in_reg("PYTHONPATH", PEP582_PATH)
return
lib_path = PEP582_PATH.replace("'", "\\'")
if shell == "AUTO":
shell = shellingham.detect_shell()[0]
shell = shell.lower()
lib_path = PEP582_PATH.replace("'", "\\'")
if shell in ("zsh", "bash"):
result = f"export PYTHONPATH='{lib_path}':$PYTHONPATH"
elif shell == "fish":
result = f"set -x PYTHONPATH '{lib_path}' $PYTHONPATH"
elif shell == "powershell":
result = f'$env:PYTHONPATH="{lib_path};$env:PYTHONPATH"'
elif shell == "cmd":
result = f"set PYTHONPATH={lib_path};%PYTHONPATH%"
elif shell in ("tcsh", "csh"):
result = f"setenv PYTHONPATH '{lib_path}':$PYTHONPATH"
else:
......
from __future__ import annotations
import argparse
import os
import sys
from collections import ChainMap
from typing import TYPE_CHECKING, Optional
......@@ -411,3 +413,36 @@ def find_importable_files(project: Project) -> Iterable[Tuple[str, Path]]:
for key, module in FORMATS.items():
if module.check_fingerprint(project, project_file.as_posix()):
yield key, project_file
def set_env_in_reg(env_name: str, value: str) -> None:
"""Manipulate the WinReg, and add value to the
environment variable if exists or create new.
"""
import winreg
value = os.path.normcase(value)
with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as root:
with winreg.OpenKey(root, "Environment", 0, winreg.KEY_ALL_ACCESS) as env_key:
try:
old_value, type_ = winreg.QueryValueEx(env_key, env_name)
except FileNotFoundError:
old_value, type_ = "", winreg.REG_EXPAND_SZ
new_value = ";".join(old_value, value) if old_value else value
try:
winreg.SetValueEx(env_key, env_name, 0, type_, new_value)
except PermissionError:
stream.echo(
stream.red(
"Permission denied, please run the terminal as administrator."
),
err=True,
)
sys.exit(1)
stream.echo(
stream.green(
"The environment variable has been saved, "
"please restart the session to take effect."
)
)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册