【问题标题】:Change directory of current terminal with python cli tool使用 python cli 工具更改当前终端的目录
【发布时间】:2020-06-17 15:32:04
【问题描述】:

我正在开发一个简单的 cli 工具,用于更改当前终端窗口的项目目录。 cli 工具是使用 click 包在 python 中编写的。从我所看到的情况来看,我认为不可能更改目录,但也许有人有这样的洞察力会有所帮助。

对于示例工作流

$ pwd
/home/username
$ grab open projectA
$ pwd
/home/username/projects/projectA
$ grab open projectB
$ pwd
/home/username/projects/different/location/projectB

我确实知道的事情。

  • 使用 python os.chdir(path) 仅适用于当前脚本,执行后对终端没有影响。
  • 尝试 python subprocess.run(['cd', 'path']) 会抛出一个FileNotFoundError: [Errno 2] No such file or directory: 'cd'
  • 运行$ source change_dir.sh 将在命令行上运行,但在subprocess 中尝试将引发相同的FileNotFoundError。请注意,change_dir.sh 是一个使用 cd 更改路径的简单脚本。

我真的在寻找解决这个问题的方法,或者被告知这是不可能的。 我可能会尝试的下一件事是在终端中使用 bash shell,类似于使用 python 启动虚拟环境时发生的情况。 对我来说,这感觉像是错误的方式。

任何建议都会有所帮助。

【问题讨论】:

  • cdsource 是 shell 内置命令,不是非 shell 可以随意执行的独立命令。
  • Been shell builtins 很有意义,谢谢。比解释为什么虚拟环境激活脚本有# This file must be used with "source bin/activate" *from bash* # you cannot run it directly 我想我可能会看一个不同的想法。也许像grab path projectA | cd 这样的东西是可能的。我需要调查一下。
  • 您找到解决方案了吗?我正在尝试做同样的事情,但来自一个快速的 cli。在最坏的情况下,我想告诉 applescript 打开一个新选项卡并运行 cd 命令

标签: python bash command-line-interface


【解决方案1】:

你可以创建一个函数

grab() {
    case "$1" in
        open)
            cd $(command grab open "$2");;

        *)
            command grab "$@";;
    esac
}

在你的 bash 中加载它

$ . grab.sh

然后,当你运行时

$ grab open projA

将更改目录,以及任何其他子命令

$ grab other whatever

它将运行grab

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-10
    • 2016-06-20
    • 2014-01-14
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多