commands模块问题
你好,我正在尝试通过导入命令模块在Python中执行bash命令。我想我之前在这里问过同样的问题。不过这次不管用。
脚本如下:
#!/usr/bin/python
import os,sys
import commands
import glob
path= '/home/xxx/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')
for bamfile in bamfiles:
fullpath = os.path.join(path,bamfile)
txtfile = commands.getoutput('/share/bin/samtools/samtools ' + 'view '+ fullpath)
line=txtfile.readlines()
print line
这个samtools view命令会生成一个(我认为是).txt文件
我遇到了以下错误:
Traceback (most recent call last):
File "./try.py", line 12, in ?
txtfile = commands.getoutput('/share/bin/samtools/samtools ' + 'view '+ fullpath)
File "/usr/lib64/python2.4/commands.py", line 44, in getoutput
return getstatusoutput(cmd)[1]
File "/usr/lib64/python2.4/commands.py", line 54, in getstatusoutput
text = pipe.read()
SystemError: Objects/stringobject.c:3518: bad argument to internal function
看起来是commands.getoutput这个部分出了问题
谢谢
2 个回答
2
我建议你使用 subprocess 这个模块。
根据命令文档的说明:
自2.6版本起,这个命令模块就不再推荐使用了:在Python 3.0中已经被移除了。建议使用subprocess模块。
更新:我刚意识到你在用Python 2.4。一个简单的执行命令的方法是 os.system()。
1
快速在谷歌上搜索“SystemError: Objects/stringobject.c:3518: bad argument to internal function”会发现几个错误报告。例如,https://www.mercurial-scm.org/bts/issue1225 和 http://www.modpython.org/pipermail/mod_python/2007-June/023852.html。看起来这个问题是Fedora系统和Python 2.4一起使用时出现的,但我不太确定。建议你听从Michael的建议,使用os.system或os.popen来完成这个任务。要做到这一点,你需要在代码中做以下更改:
import os,sys
import glob
path= '/home/xxx/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')
for bamfile in bamfiles:
fullpath = os.path.join(path,bamfile)
txtfile = os.popen('/share/bin/samtools/samtools ' + 'view '+ fullpath)
line=txtfile.readlines()
print line