使用python命令行参数的例子

# coding=utf-8
from sys import*

class Stack:
def __init__(self):
self.items=[];
def top(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop();

def Judgeoutput(arr):
flag=0;
sign='+-*/^()'
number='0123456789'
for i in range(len(arr)):
if(sign.find(arr[i])==-1 and number.find(arr[i])==-1):
print("输出:"+"INPUT ERROR\n");flag=1;break;
elif(sign.find(arr[i])!=-1 and sign.find(arr[i])<5):
if(i==0 or i==len(arr)):
print("输出:"+"FORMAT ERROR\n");flag=1;break;
elif(sign.find(arr[i-1])!=-1 or sign.find(arr[i+1])!=-1):
print("输出:"+"FORMAT ERROR\n");flag=1;break;

if(flag==0):
My_bracket=Stack()
for i in range(len(arr)):
if(arr[i]=='('):
My_bracket.push(arr[i])
elif(arr[i]==')'):
if(My_bracket.top()=='('):
My_bracket.pop();
else:
print("输出:"+"FORMAT ERROR\n");flag=1;break;
elif(i==len(arr)):
if(My_bracket.size()>=1):
print("输出:"+"FORMAT ERROR\n");flag=1;break;

if(flag==0):
for i in range(len(arr)-1):
if(arr[i]=='/' and arr[i+1]=='0'):
print("输出:"+"VALUE ERROR\n");flag=1;break;

if(flag==0):
for i in range(len(arr)):
if(arr[i]=='^'):
arr=arr.replace(arr[i],'**')

result=str(eval(arr))
if(len(result)-result.find('.')>10):
result=str(round(eval(arr),10))
print("输出:"+result+'\n')

 

if __name__=="__main__":
#print(argv)
expression='';
for i in range(1,len(argv)):
for j in range(len(argv[i])):
if(argv[i][j]!=' '):
expression+=argv[i][j]
print()
print("输入:"+str(expression)+'\n')
Judgeoutput(expression)

posted @ 2018-04-10 21:11  阳光yoyo  阅读(225)  评论(0编辑  收藏  举报