将元字符传递给Python作为命令行的参数 [英] Passing meta-characters to Python as arguments from command line
问题描述
optparse
来做到这一点。我遇到的问题是,输入像 \t
的内容会在 \t
上单独分隔,而不是在选项卡上,这是我想要的。我很确定这是一个Python的东西,而不是shell,因为我已经尝试了每一个引号,反斜杠和 t
的组合,我可以想到。 如果我可以得到 optparse
让参数是纯输入(有这样的事情吗?)而不是 raw_input
,我认为这样会奏效。但是我不知道如何做到这一点。
我也尝试过各种替代和正则表达式,从两个角色 \t
到一个字符选项卡,但没有成功。
示例,其中 input.txt
是:
field 1 [tab] field\t2
(注意: [tab]
是一个制表符, field\t2
是一个8个字符的字符串)
parseme.py:
来自optparse导入的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ par action =store,type =string,
dest =delimiter,default ='\t')
parser.add_option( - f,dest =filename b $ b(options,args)= parser.parse_args()
Infile = open(options.filename,'r')
Line = Infile.readline()
Fields = Line.split(options.delimiter)
打印字段[0]
print options.delimiter
Infile.close()
这给了我:
$ parseme.py -f input.txt
字段1
[
嘿,很好,默认设置正常工作。 (是的,我知道我可以默认并忘记它,但我想知道如何处理这种类型的问题。)
$ parseme.py -f input.txt -d'\t'
field 1 [tab] field
\t
$ 解决方案
>>> r'\t\\\
\v\r'.decode('string-escape')
'\t\\\
\x0b\r'
I'm making a Python program that will parse the fields in some input lines. I'd like to let the user enter the field separator as an option from the command line. I'm using optparse
to do this. I'm running into the problem that entering something like \t
will separate literally on \t
, rather than on a tab, which is what I want. I'm pretty sure this is a Python thing and not the shell, since I've tried every combo of quotes, backslashes, and t
's that I can think of.
If I could get optparse
to let the argument be plain input (is there such a thing?) rather than raw_input
, I think that would work. But I have no clue how to do that.
I've also tried various substitutions and regex tricks to turn the string from the two character "\t"
into the one character tab, but without success.
Example, where input.txt
is:
field 1[tab]field\t2
(Note: [tab]
is a tab character and field\t2
is an 8 character string)
parseme.py:
#!/usr/bin/python
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-d", "--delimiter", action="store", type="string",
dest="delimiter", default='\t')
parser.add_option("-f", dest="filename")
(options, args) = parser.parse_args()
Infile = open(options.filename, 'r')
Line = Infile.readline()
Fields = Line.split(options.delimiter)
print Fields[0]
print options.delimiter
Infile.close()
This gives me:
$ parseme.py -f input.txt
field 1
[tab]
Hey, great, the default setting worked properly. (Yes, I know I could just make \t the default and forget about it, but I'd like to know how to deal with this type of problem.)
$ parseme.py -f input.txt -d '\t'
field 1[tab]field
\t
This is not what I want.
解决方案 >>> r'\t\n\v\r'.decode('string-escape')
'\t\n\x0b\r'
这篇关于将元字符传递给Python作为命令行的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!