【问题标题】:Why does using virtualenv commands in .sh file give "command not found"? [duplicate]为什么在 .sh 文件中使用 virtualenv 命令会给出“找不到命令”? [复制]
【发布时间】:2015-03-27 05:39:04
【问题描述】:

我正在尝试在 Mac(小牛队)上自动删除和重新创建 virtualenv。

我有一个文件clean_venv.sh:

#!/bin/bash
echo "Start"
deactivate
rmvirtualenv test
mkvirtualenv test

这给出了:

Start
./clean_venv.sh: line 3: deactivate: command not found
./clean_venv.sh: line 4: rmvirtualenv: command not found
./clean_venv.sh: line 5: mkvirtualenv: command not found

但是,在同一位置运行命令可以正常工作。为什么是这样?

【问题讨论】:

  • 你的标题写着sh,但标签和问题写着bash。这是两个不同的外壳。 Bash 与股票 Bourne shell 向上兼容,但它们是不同的;即使/bin/sh 是 Bash 的符号链接,它也会导致 Bash 在 POSIX 兼容模式下运行,从而以多种方式改变其行为。
  • 我的意思是.sh - 为了清楚起见,我修改了标题。不过,也许是一种更好的表达方式。另外,我找到了一个解决方法,我已发布为答案

标签: macos bash sh


【解决方案1】:

虚拟环境是您当前 shell 进程的一个特性。启动一个新的 shell 进程(如运行一个 shell 脚本)会创建一个不继承虚拟环境的新进程。

鉴于此,您实际上不需要deactivate。一旦您确保其他命令在您的PATH 中,或者,如果它们是函数,则可以调用其他命令,从虚拟环境的启动文件中导入。

或者,在您当前的 shell 中定义一个函数,然后使用它。

clean_venv () {
    echo "Useless noise here."
    deactivate
    rmvirtualenv test
    mkvirtualenv test
}

【讨论】:

    【解决方案2】:

    this question 启发,我发现这段代码可以工作:

    #!/bin/bash
    source `which virtualenvwrapper.sh`
    mkvirtualenv temp    # This makes sure I'm not on the test virtualenv,      
    workon temp          # otherwise I can't delete it. deactivate doesn't
                         # work for some reason
    rmvirtualenv test
    mkvirtualenv test
    workon test
    rmvirtualenv temp
    pip install -r requirements.txt; 
    

    这感觉很hacky,但它达到了预期的结果。更新 requirements.txt 后,一个命令可以从头开始重新创建 virtualenv。最后我有一个虚拟环境 (test) 和 temp 不再存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 2020-09-01
      • 2021-07-07
      • 2019-08-10
      相关资源
      最近更新 更多