【发布时间】:2019-11-01 14:30:54
【问题描述】:
从在 Fish shell 上运行并支持 Python 2.7 和 3.4+ 的基于 Python 的安装脚本中,我想将一个目录添加到 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 运行的 Python 脚本也将是该 shell 实例的子进程。
标签: python shell subprocess fish