简体   繁体   English

在python中使用正则表达式解析语句字符串以获取参数

[英]parse statement string for arguments using regex in Python

I have user input statements which I would like to parse for arguments. 我有要解析的用户输入语句。 If possible using regex. 如果可能,使用正则表达式。

I have read much about functools.partial on Stackoverflow where I could not find argument parsing. 我在Stackoverflow上阅读了很多有关functools.partial的内容,在其中找不到参数解析。 Also in regex on Stackoverflow I could not find how to check for a match, but exclude the used tokens. 同样在Stackoverflow的正则表达式中,我找不到如何检查匹配项,但排除了使用的令牌。 The Python tokenizer seems to heavy for my purpose. Python标记器似乎很重。

import re

def getarguments(statement):      
    prog = re.compile("([(].*[)])")
    result = prog.search(statement) 
    m = result.group()  
    # m = '(interval=1, percpu=True)'
    # or m = "('/')"
    # strip the parentheses, ugly but it works
    return statement[result.start()+1:result.end()-1] 

stm = 'psutil.cpu_percent(interval=1, percpu=True)'
arg_list = getarguments(stm) 
print(arg_list) # returns : interval=1, percpu=True

# But combining single and double quotes like
stm = "psutil.disk_usage('/').percent"
arg_list = getarguments(stm) # in debug value is "'/'"   
print(arg_list) # when printed value is : '/'

callfunction = psutil.disk_usage
args = []
args.append(arg_list)
# args.append('/')
funct1 = functools.partial(callfunction, *args)
perc = funct1().percent
print(perc)  

This results an error : builtins.FileNotFoundError: [Errno 2] No such file or directory: "'/'" 这将导致错误:Builtins.FileNotFoundError:[Errno 2]没有这样的文件或目录:“'/'”

But

callfunction = psutil.disk_usage
args = []
#args.append(arg_list)
args.append('/')
funct1 = functools.partial(callfunction, *args)
perc = funct1().percent
print(perc)  

Does return (for me) 20.3 This is correct. 确实返回(对我来说)20.3这是正确的。 So there is somewhere a difference. 所以有一些区别。

The weird thing is, if I view the content in my IDE (WingIDE) the result is "'/'" and then, if I want to view the details then the result is '/' 奇怪的是,如果我在IDE(WingIDE)中查看内容,则结果为“ /”,然后,如果我要查看详细信息,则结果为“ /”

I use Python 3.4.0 What is happening here, and how to solve? 我使用的是Python 3.4.0,这是怎么回事,如何解决? Your help is really appreciated. 非常感谢您的帮助。

getarguments("psutil.disk_usage('/').percent") returns '/' . getarguments("psutil.disk_usage('/').percent")返回'/' You can check this by printing len(arg_list) , for example. 例如,您可以通过打印len(arg_list)进行检查。

Your IDE adds " , because by default strings are enclosed into single quotes ' . Now you have a string which actually contains ' , so IDE uses double quotes to enclose the string. 您的IDE会添加" ,因为默认情况下字符串被括在单引号' 。现在您有了一个实际上包含'的字符串,因此IDE使用双引号将其括起来。

Note, that '/' is not equal to "'/'" . 注意, '/'不等于"'/'" The former is a string of 1 character, the latter is a string of 3 characters. 前者是1个字符的字符串,后者是3个字符的字符串。 So in order to get things right you need to strip quotes (both double and single ones) in getarguments . 因此,为了正确处理,您需要在getargumentsgetarguments引号(双引号和单引号)。 You can do it with following snippet 您可以按照以下代码段进行操作

if (s.startswith('\'') and s.endswith('\'')) or 
        (s.startswith('\"') and s.endswith('\"')):
   s = s[1:-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM