【问题标题】:How to run a bash script from a python file? [duplicate]如何从 python 文件运行 bash 脚本? [复制]
【发布时间】:2021-10-20 07:11:00
【问题描述】:

我想从 python 脚本中运行以下 bash 脚本。

condo activate bne
CUDA_VISIBLE_DEVICES=1 python bne.py --model models/BNE_SGsc --fe ./embeddings/BioEmb/Emb_SGsc.txt --fi names.txt --fo output_BNE_SGsc.txt

我的python脚本/函数如下-

def do_tensorflow_routine(path_name_file):
    os.chdir(os.path.join("../","bne_resources/"))
    os.system("conda activate bne")
    bne_command = "python bne.py --model models/BNE_SGsc --fe ./embeddings/BioEmb/Emb_SGsc.txt --fi names.txt --fo names_bne_SGsc.txt"
    subprocess.run(bne_command,shell=True)
    pass

但是,我收到以下错误 -

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

我使用的是集群,我的系统规格如下-

   Static hostname: lab1
         Icon name: computer-server
           Chassis: server
        Machine ID: 104265a0ea5b48c1a3c5a9802294af66
           Boot ID: 4277780744ae448292d66a9ff39c76e2
  Operating System: Ubuntu 20.04.1 LTS
            Kernel: Linux 5.8.0-36-generic
      Architecture: x86-64

如果我遗漏了什么,请告诉我。我的基本问题是如何从给定的 python 脚本运行另一个 python 脚本,特别是当我们需要激活和停用虚拟环境时,因为父 python 脚本和子 python 脚本由于一些依赖冲突需要 2 个不同的虚拟环境。 请帮助我。 提前致谢, 呸

【问题讨论】:

  • os.system("conda activate bne") 仅在 os.system() 启动的 shell 中工作,os.system() 完成运行后立即退出。这并不意味着conda activate 没有运行,但它确实意味着每个os.system() 调用都是独立的——你不能指望一个这样的调用来改变shell 的状态由未来的人开始。
  • 您需要 both conda activate 依赖它的代码从 same @ 运行987654331@ 实例。
  • 嗨@CharlesDuffy - 感谢您的回复。我看到了你提到的与此类似的相关帖子,我尝试将语句修改为以下 - `subprocess.run(f"""conda init bash conda activate bne python bne.py --model models/BNE_SGsc - -fe ./embeddings/BioEmb/Emb_SGsc.txt --fi names.txt --fo names_bne_SGsc.txt conda deactivate bne""",shell=True, executable='/bin/bash', check=True)` 但是,我一直得到与原帖中提到的相同的CommandNotFoundError。如果我遗漏了什么,请告诉我。再次感谢您!
  • 您能否编辑问题以显示尝试(根据现有问题的答案)和新错误?我怀疑某些格式在将其放入评论时丢失了,细节很关键。
  • 部分可能的问题是conda init 修改了点文件,但非交互式shell 不读取 点文件并且不会从这些修改中获得任何好处。

标签: python-3.x bash shell ubuntu virtualenv


【解决方案1】:

如果运行 conda activate bne 后终端不显示(base),则尝试运行:

conda init

在顶部的 bash 脚本中,您需要 shebang 行 #!/usr/bin/env bash 并且 env 用于为不同的 Linux 发行版提供可移植性。

【讨论】:

  • OP 根本没有在终端中运行conda activate;他们在由 Python 进程启动的非交互式 shell 中运行它。查看终端提示显示的内容的建议完全没有意义/无关紧要。除此之外,这个问题已经在网站的其他地方被问过和回答了;在 How to Answer 中,请注意 Answer Well-Asked Questions 部分,以及其中关于“之前已经被多次询问和回答过”的问题的要点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 2014-12-02
  • 2013-03-14
  • 1970-01-01
  • 2023-04-07
  • 2017-09-21
  • 1970-01-01
相关资源
最近更新 更多