Python subprocess 命令行解析错误

0 投票
3 回答
978 浏览
提问于 2025-04-18 04:06

我正在运行一个用Python编写的程序,这个程序使用了一个叫做WolfPsort的子程序。这个工具是用来检测蛋白质定位的。

但是,Python的子程序没有执行我的输入文件。以下是我的代码:

#!/usr/bin/python
# secref.py is for secretome refining

import os
import sys
import subprocess

if len(sys.argv) != 2:
        print >> sys.stderr, 'Usage: python secref.py [*.fasta]'
        exit(1)

if sys.argv[1].endswith('.fasta'):
        filename = sys.argv[1]
else:
        print >> sys.stderr, 'Input correct file... [*.fasta]'
        exit(1)

filehandle = open(filename,'r')

progWolf = subprocess.Popen(['runWolfPsortSummary','fungi','<',filename,'>','tmpWolfResult'])
progWolf.wait()

当我运行这段代码时,它会给出这样的错误信息:

[karyo@hostname secref.1.0]$ python secref.py A.carbonarius.fasta 

Command Line Parsing Error; Do not know what to do with argument "<"

Usage:
    runWolfPsortSummary [*OPTIONS*] *organismType*

    runWolfPsortSummary (--usage|--help|--man)

    Pipe sequences in from standard in.

子程序不识别"<"这个符号,但WolfPsort程序需要"<"来识别输入的fasta文件,而">"则是用来写入临时结果文件的。

我该如何让子程序理解"<"这个参数呢?

请帮帮我!

3 个回答

0

Popen这个函数需要用逗号分开的参数列表。你写的方式,

'<'
filename
'>'

会被当作三个不同的参数来处理。我猜你是想把它们合并成一个参数。

progWolf = subprocess.Popen(['runWolfPsortSummary','fungi','<' + filename + '>','tmpWolfResult'])
1

< 和 > 通常会被命令行解释,所以在默认情况下,Popen() 不会多余地启动进程。你可以使用 stdinstdout 参数来将输入/输出重定向到文件。

from subprocess import check_call

with open(filename) as file, open('tmpWolfResult', 'w') as output_file:
    check_call(['runWolfPsortSummary', 'fungi'], stdin=file, stdout=output_file)

注意:如果 runWolfPsortSummary 以非零状态退出,check_call() 会抛出一个异常。

2

我猜你是想用一些命令行的技巧,从文件名中读取内容,然后把结果写入tmpWolfResult。为了实现这个,你需要:

progWolf = subprocess.Popen('runWolfPsortSummary fungi < %s > tmpWolfResult'%filename, shell=True)

我觉得有必要提一下,因为这个输入是来自命令行参数,所以从技术上讲,它并不是很安全/可信。如果有恶意用户能够在你的系统上运行这个脚本,他们可能会做一些很糟糕的事情。

不过,可能更常见的情况是,你是在分发这个脚本(或者只是自己使用),你和你的用户大概也不想搞坏自己的系统……

撰写回答