2011-08-18 106 views
0

嗨我想通過導入命令module.py在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查看會產生(我認爲).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 

似乎這是command.getoutput的問題

謝謝

+0

這不會解決你所遇到的問題,但你將有一個未來的問題是,commands.getoutput()返回一個字符串,你調用readlines方法( ) 在上面。這將失敗,因爲readlines()是一個文件對象的操作。 – bschaffer13

回答

1

快速谷歌搜索「SystemError:Objects/stringobject.c:3518:壞內部函數的參數」提出了幾個錯誤報告。如https://www.mercurial-scm.org/bts/issue1225http://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 
2

我會建議使用subprocess

從命令文件:

Deprecated since version 2.6: The commands module has been removed in Python 3.0. Use the subprocess module instead.

更新:只要你使用Python 2.4實現。一個簡單的方法來執行一個命令是os.system()

+1

我同意他應該使用子進程,但是我不知道它是否會解決問題。命令能夠被導入,這意味着他可能使用支持命令的python版本。因此它應該仍然有效。 – bschaffer13

+0

是的,我注意到2.4版本有點晚。更新到帖子應該有所幫助。 – 2011-08-18 21:49:05

+1

os.system()不會讓他得到他需要的輸出os.popen()將是一個更好的選擇。 – bschaffer13