2014-01-17 2 views
1

나는 다음과 같은 기능이 있습니다파이썬 정규식 구문

def handleRequest(self, command, ident, ip, duration=0): 
    if not re.match("^[0-9]+$", ident) or not re.match("^[0-9.]+$", ip) or \ 
     (duration and not re.match("^[0-9]+$", duration)): 
     print ("Unknown command") 
     return 

    if command == "DOTHIS": 
     reactor.callInThread(self.func, ident, "./DOTHIS.sh", ip, 0, command) 
    elif command == "DOTHAT": 
     reactor.callInThread(self.func, ident, "./DOTHAT.sh", ip, 0, command) 
    elif command == "DOTHAT": 
     reactor.callInThread(self.func, ident, "./DOTHING.sh", ip, duration, command) 
    elif command == "DOMORETHINGS": 
     reactor.callInThread(self.func, ident, "./DOMORETHINGS.sh", ip, duration, command) 
    else: 
     print ("Unknown command") 
     return 

내 서버에 특정 스크립트를 실행하기 위해이 기능을 사용합니다. 내 문제는 실행되는 명령 (DOTHIS, DOTHAT 등)의 올바른 구문입니다. 정규식과 관련이 있어야합니다. 명령에 여러 매개 변수가있을 수 있습니다 (예 : DOTHIS 127.0.0.1).

아무리 명령을 쿼리해도 결과는 항상 "알 수없는 명령"입니다.

누구나 올바른 구문을 사용하여 명령의 예를 제공 할 수 있습니까 (몇 가지 매개 변수 포함).

감사합니다.

+4

어떤 알 수없는 명령이 인쇄되고 있습니까? 첫 번째 또는 두 번째'print ("알 수없는 명령")' –

+0

코드에 문제가 없습니다! 어떻게 부르는지 몇 가지 사례를 게시 할 수 있습니까? –

+0

기본적으로 내 서버에 터미널 연결을 만들고 내가 원하는 명령을 제공합니다. 예를 들어 PING 127.0.0.1 80 (PING.sh를 실행하고 ping을 127.0.0.1 포트 80으로 시작해야 함)입니다. 또한, 나는 그것이 최초의 "알려지지 않은 명령"이라고 생각한다. – user3208125

답변

0

re.match("^[0-9.]+$", number)

일치 숫자 만 포함하는 모든 문자열.

그래서 당신은 할 수 있어야한다 :

def handleRequest(self, command = '0', ident = '0', ip = '0', duration='0'): 

사용 help('re')는 문자가 무엇을 의미하는지에 대해 알아.

0

(handleRequest) 입력 샘플은 무엇입니까?

즉, 명령의 경우? IP를 가정

= '127.0.0.1', 지속 시간 = '10 '문자열이 단지 숫자가 포함 된 경우

이 참고로,이 조건이 항상 출력이 거짓합니다.

(duration and not re.match("^[0-9]+$", duration)) 
0

이것은 모든 인수가 문자열 가정,하지만이 작동합니다 : 만약 그렇다면 있도록

import re 

def handleRequest(self, command, ident, ip, duration=0): 
    returnEarly = 0 
    if not re.match("^\d+$", ident): 
     print ("Invalid ident") 
     returnEarly = 1 
    if not re.match("^[\d.]+$", ip): 
     print ("Invalid ip") 
     returnEarly = 1 
    if (duration and not re.match("^\d+$", duration)): 
     print ("Invalid Duration") 
     returnEarly = 1 

    if returnEarly: 
     return 

    if command == "DOTHIS": 
     print ("DOTHIS") 
    elif command == "DOTHAT": 
     print ("DOTHAT") 
    elif command == "DOTHING": 
     print ("DOTHING") 
    elif command == "DOMORETHINGS": 
     print ("DOMORETHING") 
    else: 
     print ("Unknown command") 


handleRequest("", "DOTHIS", "11", "127.0.0.1", "10") # works 
handleRequest("", "BADCOMMAND", "11", "127.0.0.1", "10") # fails on command 
handleRequest("", "DOTHIS", "11C", "127.0.0B.1", "A10") # fails on arguments 

내가 숫자 파이썬에서 "\ D"정규식 바로 가기를 사용, 또한 각 검사 명시했다 이유를 알지 못한다. 문자열이 아닌 인수를 전달하는 경우 검사하기 전에 str (argX)을 사용하여 문자열로 변환 할 수 있습니다. 이것을 테스트하기 위해 Python 2.7을 사용했습니다.

편집 : 나는 또한 내가 게으르게 클래스의이 방법 부분을하지 않았 음을 지적하고, 단지 자기의 빈 문자열로 전달한다.