为什么我不能用python和optparse运行脚本

时间:2013-10-23 12:18:11

标签: python optparse

我遇到了一个我无法理解的问题。我正在做我已经完成的事情以及我面临的问题。

这是我的代码:

#! /usr/bin/env python

import os

from dvbobjects.PSI.PAT import *
from optparse import OptionParser

#
# Shared values
#


parser = OptionParser()
parser.add_option( "--tsid",
                 help="input transportstream id", metavar="FILE")
(options, args) = parser.parse_args()

#############

avalpa_transport_stream_id = options.tsid # demo value, an official value should be demanded to dvb org
avalpa_original_transport_stream_id = 1#options.otsid # demo value, an official value should be demanded to dvb org
avalpa1_service_id = 1 # demo value
avalpa1_pmt_pid = 2031 #options.spmtid
output= './pat.ts'


#
# Program Association Table (ISO/IEC 13818-1 2.4.4.3)
#

pat = program_association_section(
   transport_stream_id = avalpa_transport_stream_id,
        program_loop = [
           program_loop_item(
           program_number = avalpa1_service_id,
          PID = avalpa1_pmt_pid,
           ),  
           program_loop_item(
           program_number = 0, # special program for the NIT
          PID = 16,
           ), 
        ],
        version_number = 1, # you need to change the table number every time you edit, so the decoder will compare its version with the new one and update the table
        section_number = 0,
        last_section_number = 0,
        )

#
# PSI marshalling and encapsulation
#

out = open("./pat.sec", "wb")
out.write(pat.pack())
out.close
out = open("./pat.sec", "wb") # python   flush bug
out.close
os.system('/usr/local/bin/sec2ts 0 < ./pat.sec > '+ output)


#remove all sec files
os.system('rm *.sec')

并查询:./patconfig.py --tsid 1

和错误:

Traceback (most recent call last):
  File "./patconfig.py", line 86, in <module>
    out.write(pat.pack())
  File "/usr/local/lib/python2.6/dist-packages/dvbobjects/MPEG/Section.py", line 94, in pack
    self.__sanity_check()
  File "/usr/local/lib/python2.6/dist-packages/dvbobjects/MPEG/Section.py", line 68, in __sanity_check
    assert 0 <= self.table_id_extension <= 0xffff
AssertionError

请帮助我。我无法理解这个问题,当我不使用optparser时,脚本运行正常!!

1 个答案:

答案 0 :(得分:0)

您需要关闭输出文件。

当你输入out.close时,它实际上只是返回对函数的引用。您需要使用

调用该函数
out.close()

而不是

out.close

看看它是否有效,如果没有发表评论,我会看到我能发现的其他内容,但首先是基础知识。

In [7]: out = open('test', 'wb')

In [8]: out
Out[8]: <open file 'test', mode 'wb' at 0x052C7180>

In [9]: out.close
Out[9]: <function close>

In [10]: out
Out[10]: <open file 'test', mode 'wb' at 0x052C7180>

In [11]: out.close()

In [12]: out
Out[12]: <closed file 'test', mode 'wb' at 0x052C7180>