在 python 中获取命令行参数作为元组

发布于 2024-10-23 18:37:34 字数 1805 浏览 4 评论 0原文

以下是我如何调用脚本的示例:

python script.py -f file1.txt "string1" "string2" -f file2.txt "string3" "string4"

作为输入的每个文件都将有 2 个与该文件关联的字符串。可以有任意数量的文件。

为了简化,我试图得到这样的打印:

('file1.txt', 'string1', 'string2')
('file2.txt', 'string3', 'string4')

这是到目前为止我所得到的:

import sys, os, traceback, optparse
import time
import re
#from pexpect import run, spawn

def main ():
    global options, args

    print options.filename

    #for filename in options.filename:
    #  print filename
      #f = file(filename,'r')
      #for line in f:
      #  print line,
      #f.close()



if __name__ == '__main__':
    try:
        start_time = time.time()
        parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id$')
        parser.add_option ('-f', '--file', dest='filename', help='write report to FILE', metavar='FILE', nargs=3)
        parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output')
        (options, args) = parser.parse_args()
        #if len(args) < 1:
        #    parser.error ('missing argument')
        if options.verbose: print time.asctime()
        main()
        if options.verbose: print time.asctime()
        if options.verbose: print 'TOTAL TIME IN MINUTES:',
        if options.verbose: print (time.time() - start_time) / 60.0
        sys.exit(0)
    except KeyboardInterrupt, e: # Ctrl-C
        raise e
    except SystemExit, e: # sys.exit()
        raise e
    except Exception, e:
        print 'ERROR, UNEXPECTED EXCEPTION'
        print str(e)
        traceback.print_exc()
        os._exit(1)

使用上面的脚本,我只得到第二个文件和相关字符串:

('file2.txt', 'string3', 'string4')

Here is an example of how I would like to call my script:

python script.py -f file1.txt "string1" "string2" -f file2.txt "string3" "string4"

Every file that goes as input will have 2 strings associated with that file. There can be any number of files.

To simplify, I am trying to get a print like this:

('file1.txt', 'string1', 'string2')
('file2.txt', 'string3', 'string4')

Here is what I have so far:

import sys, os, traceback, optparse
import time
import re
#from pexpect import run, spawn

def main ():
    global options, args

    print options.filename

    #for filename in options.filename:
    #  print filename
      #f = file(filename,'r')
      #for line in f:
      #  print line,
      #f.close()



if __name__ == '__main__':
    try:
        start_time = time.time()
        parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id

With the above script, I get only the second file and related strings:

('file2.txt', 'string3', 'string4')
) parser.add_option ('-f', '--file', dest='filename', help='write report to FILE', metavar='FILE', nargs=3) parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output') (options, args) = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if options.verbose: print time.asctime() main() if options.verbose: print time.asctime() if options.verbose: print 'TOTAL TIME IN MINUTES:', if options.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1)

With the above script, I get only the second file and related strings:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

So要识趣 2024-10-30 18:37:35

如果您因为想要与 python 2.6 保持兼容而使用 optparse,则 action='append' 解决方案也适用:

import optparse

parser = optparse.OptionParser()
parser.add_option('-f', '--file', dest='filename', nargs=3, action='append')

演示

>>> (opts, args)  = parser.parse_args("-f file1.txt string1 string2 -f file2.txt string3 string4".split())
>>> for fn_tuple in opts.filename:
...    print fn_tuple
('file1.txt', 'string1', 'string2')
('file2.txt', 'string3', 'string4')

If you are using optparse because you want to remain compatible with python 2.6, the action='append' solution works, too:

import optparse

parser = optparse.OptionParser()
parser.add_option('-f', '--file', dest='filename', nargs=3, action='append')

Demonstration

>>> (opts, args)  = parser.parse_args("-f file1.txt string1 string2 -f file2.txt string3 string4".split())
>>> for fn_tuple in opts.filename:
...    print fn_tuple
('file1.txt', 'string1', 'string2')
('file2.txt', 'string3', 'string4')
糖果控 2024-10-30 18:37:34

我认为您想使用 add_argument 方法的 action=append 参数

import argparse

parser= argparse.ArgumentParser()
parser.add_argument ('-f', '--file', nargs=3, action='append')

files = parser.parse_args('-f file1 string1 string2 -f file2 string3 string4 -f file3 string5 string6'.split()).file

for f in files:
    print tuple(f)

给您:

('file1', 'string1', 'string2')
('file2', 'string3', 'string4')
('file3', 'string5', 'string6')

在 cli 上测试:

与:

import argparse

parser= argparse.ArgumentParser(prog='Test', usage='%(prog)s -f Filename Option1 Option2 ')
parser.add_argument ('-f', '--file', nargs=3, action='append')

files = parser.parse_args().file

for f in files:
    print tuple(f)

结果:

python test.py -f file1 "foo bar" "baz" -f file2 foo bar
('file1', 'foo bar', 'baz')
('file2', 'foo', 'bar')

python test.py -f file1 "foo bar" "string2" -f file2 foo bar -f file3 "foo" "bar"
('file1', 'foo bar', 'string2')
('file2', 'foo', 'bar')
('file3', 'foo', 'bar')

python test.py -f file1 "foo bar"
usage: Test -f Filename Option1 Option2
Test: error: argument -f/--file: expected 3 argument(s)

I think you want to use the action=append argument of the add_argument method

import argparse

parser= argparse.ArgumentParser()
parser.add_argument ('-f', '--file', nargs=3, action='append')

files = parser.parse_args('-f file1 string1 string2 -f file2 string3 string4 -f file3 string5 string6'.split()).file

for f in files:
    print tuple(f)

gives you:

('file1', 'string1', 'string2')
('file2', 'string3', 'string4')
('file3', 'string5', 'string6')

Testing on cli:

with:

import argparse

parser= argparse.ArgumentParser(prog='Test', usage='%(prog)s -f Filename Option1 Option2 ')
parser.add_argument ('-f', '--file', nargs=3, action='append')

files = parser.parse_args().file

for f in files:
    print tuple(f)

results:

python test.py -f file1 "foo bar" "baz" -f file2 foo bar
('file1', 'foo bar', 'baz')
('file2', 'foo', 'bar')

python test.py -f file1 "foo bar" "string2" -f file2 foo bar -f file3 "foo" "bar"
('file1', 'foo bar', 'string2')
('file2', 'foo', 'bar')
('file3', 'foo', 'bar')

python test.py -f file1 "foo bar"
usage: Test -f Filename Option1 Option2
Test: error: argument -f/--file: expected 3 argument(s)
枯寂 2024-10-30 18:37:34

argparse 支持累加器的概念,它允许您指定多个相同的选项一次,这可能比 optparse 支持的任何东西都更像你想要的(你的特殊问题是 optparse 不知道如何处理多次指定的参数,所以这是命令行中的“最后一个获胜”)。 argparse 包含在 Python 2.7 和 3.2 中,但您应该能够下载它 适用于 2.6.x 或更高版本。

argparse supports the notion of accumulators, which allow you to specify the same option more than once, which is probably more like what you want than anything optparse supports (your particular problem is that optparse doesn't know what to do with an argument specified multiple times, so it's "last one wins" at the command line). argparse is included in Python 2.7 and 3.2, but you should be able to download it for anything 2.6.x or later.

━╋う一瞬間旳綻放 2024-10-30 18:37:34

您不太清楚您的限制,但这适用于任意数量的 -f 和其他标志

import getopt
import sys

args = sys.argv[1:]
tuples = []
while args:
    try:
        opts, args = getopt.getopt(args, "f:v", ["file", "verbose"])
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(-1)    

    for o, a in opts:
        if o in ("-f", "--file"):
            tuples.append((a, args.pop(0), args.pop(0)))
        if o in ("-v", "--verbose"):
            print "yep, verbose"

print tuples

You weren't very clear on your constraints, but this will work for any number of -fs and other flags

import getopt
import sys

args = sys.argv[1:]
tuples = []
while args:
    try:
        opts, args = getopt.getopt(args, "f:v", ["file", "verbose"])
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(-1)    

    for o, a in opts:
        if o in ("-f", "--file"):
            tuples.append((a, args.pop(0), args.pop(0)))
        if o in ("-v", "--verbose"):
            print "yep, verbose"

print tuples
终止放荡 2024-10-30 18:37:34

我的处理方法与之前的答案类似,但稍作调整:

import getopt
import sys

args = sys.argv[1:]
tuples = []
while args:
try:
    (opts, args) = getopt.getopt(args, "f:v", ["file=", "verbose"])
except getopt.GetoptError, err:
    print str(err)
    sys.exit(2)    

现在您可以通过以下方式要求输入:

-f file1.txt,string1,string2

并按以下方式解析它:

for opt, arg in opts:
    if opt in ("-f", "--file"):
        tuples.append(tuple(arg.split(",")))
    if opt in ("-v", "--verbose"):
        print "yep, verbose"
print tuples

或者将输入设计为一个字符串:

-f "file1.txt string1 string2"

然后根据您喜欢的任何内容进行拆分。

I would approach this similarly to the previous answer with a slight tweak:

import getopt
import sys

args = sys.argv[1:]
tuples = []
while args:
try:
    (opts, args) = getopt.getopt(args, "f:v", ["file=", "verbose"])
except getopt.GetoptError, err:
    print str(err)
    sys.exit(2)    

Now you can either require input in the following way:

-f file1.txt,string1,string2

And parse it in the following way:

for opt, arg in opts:
    if opt in ("-f", "--file"):
        tuples.append(tuple(arg.split(",")))
    if opt in ("-v", "--verbose"):
        print "yep, verbose"
print tuples

Or design the input as one string:

-f "file1.txt string1 string2"

and split on whatever strikes your fancy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文