如何使用 Python 脚本将目录添加到 Fish shell PATH?
How to add a directory to Fish shell PATH from with a Python script?
在 Fish shell 上基于 Python 的安装脚本 运行ning 并支持 Python 2.7 和 3.4+,我想添加一个目录到PATH
环境变量(如果尚未存在)。当脚本退出时,PATH
应该包含新目录,用于当前的 Fish shell 会话以及未来的登录。
为了实现这一点,我可以想到两种可能的方法:
- 在
~/.config/fish/conf.d/
中创建一个 localpath.fish
文件,其中包含:set PATH ~/.local/bin $PATH
- 使用Python的
subprocess
到运行:set -U fish_user_paths ~/.local/bin $fish_user_paths
我更喜欢后一种方法,但我已经尝试通过 subprocess
几种不同的方式调用 Fish,但都无济于事。例如:
>>> subprocess.check_output(["fish", "-c", "echo", "Hello", "World!"], shell=True)
在 Fish 3.0.2 和 Python 3.7.4 上,以上结果:
<W> fish: Current terminal parameters have rows and/or columns set to zero.
<W> fish: The stty command can be used to correct this (e.g., stty rows 80 columns 24).
… 并且 Python REPL 提示不再出现。点击 CTRL-C 不会正确退出,使 Python REPL 处于几乎无法使用的状态,直到退出并重新启动。 (这似乎是 known issue。)
类似地,使用 subprocess.run()
和 Python 3.7 的 capture_output
参数无法产生预期的输出:
>>> subprocess.run(["fish", "-c", "echo", "Hello", "World!"], capture_output=True)
CompletedProcess(args=['fish', '-c', 'echo', 'Hello', 'World!'], returncode=0, stdout=b'\n', stderr=b'')
我的问题:
- 有没有比以上两种方法更好的策略?
- 如果使用第一种方法,我将如何从 Python 脚本中为当前 Fish shell 会话调整
PATH
?
- 如果使用
set -U fish_user_paths […]
方法,从 Python 脚本中调用它的合适方法是什么?
您走在正确的轨道上,但整个命令必须作为单个参数。另外,您不希望事先 shell 扩展。
所以你可以这样写:
subprocess.check_output(["fish", "-c", "echo hello world"])
它会如您所愿。对于 PATH 情况:
subprocess.check_output(["fish", "-c", "set -U fish_user_paths ~/.local/bin $fish_user_paths"])
这将修改父进程中的 $PATH。
在 Fish shell 上基于 Python 的安装脚本 运行ning 并支持 Python 2.7 和 3.4+,我想添加一个目录到PATH
环境变量(如果尚未存在)。当脚本退出时,PATH
应该包含新目录,用于当前的 Fish shell 会话以及未来的登录。
为了实现这一点,我可以想到两种可能的方法:
- 在
~/.config/fish/conf.d/
中创建一个localpath.fish
文件,其中包含:set PATH ~/.local/bin $PATH
- 使用Python的
subprocess
到运行:set -U fish_user_paths ~/.local/bin $fish_user_paths
我更喜欢后一种方法,但我已经尝试通过 subprocess
几种不同的方式调用 Fish,但都无济于事。例如:
>>> subprocess.check_output(["fish", "-c", "echo", "Hello", "World!"], shell=True)
在 Fish 3.0.2 和 Python 3.7.4 上,以上结果:
<W> fish: Current terminal parameters have rows and/or columns set to zero.
<W> fish: The stty command can be used to correct this (e.g., stty rows 80 columns 24).
… 并且 Python REPL 提示不再出现。点击 CTRL-C 不会正确退出,使 Python REPL 处于几乎无法使用的状态,直到退出并重新启动。 (这似乎是 known issue。)
类似地,使用 subprocess.run()
和 Python 3.7 的 capture_output
参数无法产生预期的输出:
>>> subprocess.run(["fish", "-c", "echo", "Hello", "World!"], capture_output=True)
CompletedProcess(args=['fish', '-c', 'echo', 'Hello', 'World!'], returncode=0, stdout=b'\n', stderr=b'')
我的问题:
- 有没有比以上两种方法更好的策略?
- 如果使用第一种方法,我将如何从 Python 脚本中为当前 Fish shell 会话调整
PATH
? - 如果使用
set -U fish_user_paths […]
方法,从 Python 脚本中调用它的合适方法是什么?
您走在正确的轨道上,但整个命令必须作为单个参数。另外,您不希望事先 shell 扩展。
所以你可以这样写:
subprocess.check_output(["fish", "-c", "echo hello world"])
它会如您所愿。对于 PATH 情况:
subprocess.check_output(["fish", "-c", "set -U fish_user_paths ~/.local/bin $fish_user_paths"])
这将修改父进程中的 $PATH。