【问题标题】:How to pass command line options using python's command line shell? [duplicate]如何使用 python 的命令行 shell 传递命令行选项? [复制]
【发布时间】:2013-08-18 00:00:34
【问题描述】:

这是我的程序(test.py):

#!/usr/bin/python
import sys, getopt
def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
     main(sys.argv[1:])

使用 msdos 命令行我可以像这样传递 -h 选项(在 test.py 中定义):

python test.py -h         

然后 msdos 命令行会输出:

 test.py -i <inputfile> -o <outputfile>

但是我如何在 python 交互中传递 -h 选项 使用 msdos 命令行完成的模式?

【问题讨论】:

    标签: python


    【解决方案1】:

    也许您可以尝试使用自定义 sys.argv 来破解某些东西,但这太 hacky,请改用:

    >>> from subprocess import call
    >>> call(['./test.py', option1, option2, ...])
    

    【讨论】:

      【解决方案2】:

      if __name__ == "__main__": 行的整个想法是,该文件既可以用作程序,也可以用作模块。

      这样做:

      >>> import test
      >>> test.main(['-h'])
      

      如果您的模块没有__name__ 检查,您可以只分配给sys.argv

      >>> import sys
      >>> sys.argv = ['-h']
      >>> import test
      

      但很自然,这只会在第一次加载模块时起作用。对于下一次运行,您需要运行:

      >>> reload(test)
      

      注意:在 Python2 中 reload 是内置的,但在 Python3 中它位于模块 imp 中。

      【讨论】:

        猜你喜欢
        • 2015-03-23
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-30
        • 1970-01-01
        相关资源
        最近更新 更多