python - 在 python 中运行 python 脚本

标签 python bash

<分区>

我知道这个问题已经被问过多次,我阅读了多个问题试图解决这个问题。然而,这些都没有真正奏效。

我有一个从以下位置下载的 Python 脚本:https://github.com/endrebak/kg

我正在尝试从 python 内部运行以下命令。当我直接从终端运行它时它有效,但当我从 python 内部运行它时抛出错误:

/usr/packages/kg-master/bin/kg --mergecol=0 --noheader --genes --definition --species=hsa <(echo 01200)

使用以下代码:

pathwayID = 01200

cmd="/usr/packages/kg-master/bin/kg --mergecol=0 --noheader --genes --definition --species=hsa <(echo {})".format(pathwayID)

tmp = os.popen(cmd).read()

但是,我收到以下错误:

sh: -c: line 0: syntax error near unexpected token `('

sh: -c: line 0: `/usr/packages/kg-master/bin/kg --mergecol=0 --noheader --genes --definition --species=hsa <(echo 05200)'

我尝试了多种建议,比如在调用脚本之前添加 python

cmd="python /usr/packages/kg-master/bin/kg --mergecol=0 --noheader --genes --definition --species=hsa <(echo {})".format(pathwayID)

另一个建议是使用:

subprocess.call(['/usr/packages/kg-master/bin/kg', "--mergecol=0","--noheader","--genes","--definition","--species=hsa <(echo '01200')"])

自执行实际脚本以来,此解决方案最接近解决问题。但是,似乎参数没有正确传递,我不知道为什么。

如有任何帮助,我们将不胜感激。

最佳答案

使用 subprocess 运行此命令, 你需要使用一个理解 process substitution 的 shell语法,例如bash . /bin/sh ,这是 subprocess 使用的默认 shell , 不支持。

import subprocess

cmd = ("/usr/packages/kg-master/bin/kg --mergecol=0 --noheader --genes"
       "--definition --species=hsa <(echo {})".format(pathwayID))

process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE, executable="/usr/bin/bash")
out, err = process.communicate()

或者,您可以将 ID 保存到临时文件并使用输入重定向 (<)。

关于python - 在 python 中运行 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436601/

相关文章:

bash - 如何使用 <<< 运算符读取整行?

python - 如何设置Django包开发环境?

python - 比较 pandas 数据帧,从其他数据帧捕获数据

bash - bash 脚本函数中的并发或锁定访问

linux - 检查程序是否正在特定节点上运行

Git 自动补全 : syntax error near unexpected token `newline'

python - 使用一个参数属性作为另一个参数的默认值?

python - 我可以从外部类的类方法中调用内部类吗?

Python - 简化重复的 if 语句

linux - 在 bash 中查找文件中最常见的行