【问题标题】:run .sh script from python that initates another process从启动另一个进程的python运行.sh脚本
【发布时间】:2018-11-16 13:08:47
【问题描述】:

我在 StackOverflow 上寻找答案,但其中大多数都没有解决我的整个任务。

我有一个名为 cellprofiler 的软件,它使用自己的 GUI 并在 Ubuntu 上的 conda 环境中运行。

我想用另一个 python 脚本在外部自动运行这个 cellprofiler。

我的步骤:

1) 我在 python 中创建了一个运行环境和软件的 bash 脚本:

env_activate = 'path_to_sh/activate_env.sh'
with open(env_activate, 'w') as f:
    f.write('#!/bin/sh\n')
    f.write('. activate cellprofiler && cellprofiler')
    f.close()

2) 然后在我的 python 脚本中执行:

processCP = subprocess.Popen(env_activate, stdout=subprocess.PIPE)
processCP.wait()

但这会导致它在系统 python 解释器 3.5 中运行,而不是在 conda 环境中运行

Traceback (most recent call last):
  File "/home/**/.local/bin/cellprofiler", line 6, in <module>
    from pkg_resources import load_entry_point
  File "/home/**/.local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 3126, in <module>
    @_call_aside
  File "/home/**/.local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 3110, in _call_aside
    f(*args, **kwargs)
  File "/home/**/.local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 3139, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/home/**/.local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 581, in _build_master
    ws.require(__requires__)
  File "/home/**/.local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 898, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/home/**/.local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 784, in resolve
    raise DistributionNotFound(req, requirers)

    pkg_resources.DistributionNotFound: The 'CellProfiler' distribution was not found and is required by the application

有人知道为什么会这样吗?

更新: 我需要的python解释器是python2.7,它已经在conda环境中了。如果在终端中调用 Cellprofiler 可以正常工作:

source activate cellprofiler
cellprofiler

【问题讨论】:

  • 您是否尝试在 Popen 通话中设置 shell=True
  • @JonahBishop 是的,shell=True 会导致同样的错误,而且我想将来可能在shell=False 模式下运行它
  • 来自pkg_resources.DistributionNotFound:,看起来有些依赖没有实现。看看命令是不是手动运行的?
  • @SwadhikarC 如果我在我的环境中手动运行它效果很好

标签: python bash conda


【解决方案1】:

在终端中运行

pip install cellprofiler

【讨论】:

  • 我的 conda 环境中安装了 cellprofiler。它运行良好,它从 python 脚本中调用它作为在这个现有环境中运行的新进程的任务
【解决方案2】:

回答我自己的问题: 它有助于阅读Running subprocess within different virtualenv with python

所以,需要使用subprocess.Popen 来创建一个进程。 另一个技巧是在 bash 脚本中使用 she-ban #!/bin/bash\n。 毕竟它被创建为:

 env_activate = 'path_to/activate_env.sh'
 with open(env_activate, 'w') as f:
        f.write('#!/bin/bash\n')
        f.write('source activate cellprofiler\n')
        f.write('cellprofiler')
        f.close()

并运行:

processCP = subprocess.Popen(env_activate, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2016-09-03
    • 1970-01-01
    • 2018-07-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多