【问题标题】:How to add a directory to Fish shell PATH from with a Python script?如何使用 Python 脚本将目录添加到 Fish shell PATH?
【发布时间】:2019-11-01 14:30:54
【问题描述】:

从在 Fish shell 上运行并支持 Python 2.7 和 3.4+ 的基于 Python 的安装脚本中,我想将一个目录添加到 PATH 环境变量(如果尚不存在)。当脚本退出时,PATH 应该包含新目录,既适用于当前的 Fish shell 会话,也适用于未来的登录。

为了实现这一点,我可以想到两种可能的方法:

  1. ~/.config/fish/conf.d/ 中创建一个localpath.fish 文件,其中包含:set PATH ~/.local/bin $PATH
  2. 使用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'')

我的问题:

  1. 有比上述两种方法更好的策略吗?
  2. 如果使用第一种方法,我将如何在 Python 脚本中为当前 Fish shell 会话调整 PATH
  3. 如果使用 set -U fish_user_paths […] 方法,从 Python 脚本中调用该方法的合适方法是什么?

【问题讨论】:

  • 子进程不能影响其父进程,除非您单独安排父进程配合。从 shell 运行的 Python 脚本也将是该 shell 实例的子进程。

标签: python shell subprocess fish


【解决方案1】:

您在正确的轨道上,但整个命令必须作为单个参数。此外,您不希望事先进行 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。

【讨论】:

  • 太棒了。非常感谢您指导我正确调用!
猜你喜欢
  • 1970-01-01
  • 2019-05-12
  • 2011-03-21
  • 2018-02-21
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多