从python运行.sh脚本以启动另一个进程

时间:2018-11-16 13:08:48

标签: python bash conda

我一直在寻找关于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解释器是已经在conda环境中的python2.7。如果像在终端中那样调用Cellprofiler,它将正常工作:

source activate cellprofiler
cellprofiler

2 个答案:

答案 0 :(得分:0)

在终端中运行

pip install cellprofiler

答案 1 :(得分:0)

要回答我自己的问题: 它有助于通读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)
相关问题