我正在从websocket (ws://localhost:8080)获取数据,并使用该数据执行命令行参数。下面提到的代码…
python data .py -i 127.0.0.1 -p 8080
from websocket import create_connection
#import ConfigParser
#from test import settings
import sys
import argparse
import socket
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='ip' , help='host name / IP')
parser.add_argument('-p', dest='port' , type=int, help='port')
parser.add_argument('-t', dest='time' , type=int, help='Time (in seconds) to keep reading data from websocket. After this process will be exit. Default value is 0. For 0 it will run infinitely')
parser.add_argument('-m', dest='msg' , type=int, help='Number of message. Process will exit after receiving Number of messages. Default is 0, means runs for ever.')
args = parser.parse_args()
print(args.ip)
#ws://%s:%s" % (args.ip,args.port)
url = "ws://%s:%s" % (args.ip,args.port)
ws = create_connection(url)
print "Receiving data from the socket..."
for each in ws:
result = ws.recv();
print "Received '%s'" % result
ws.close();
控制台:
C:Users556718Desktoppythonprac>python datapy.py -i 127.0.0.1 -p 8080
127.0.0.1
Receiving data from the socket...
Received 'sound'
Received 'eokeoe'
Received 'mdmmd'
Received 'ssss'
Received 'tttt'
如argparse中所述,我想传递-m和-t - like
python data.py -i 127.0.0.1 -p 8080 -m 5 --> It will limit to only 5 messages in the console..
python data.py -i 127.0.0.1 -p 8080 -t 120 --> Send me the messages until 120 seconds - after that exit ....
python data.py -i 127.0.0.1 -p 8080 -m 5 -t 120 --> for limiting to 120 seconds (2 minutes) and 5 messages - either of the condition
有谁能帮我一下吗
我无法测试,但是沿着这些行应该可以工作。
from websocket import create_connection
#import ConfigParser
#from test import settings
import sys
import argparse
import socket
import time
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='ip' , help='host name / IP')
parser.add_argument('-p', dest='port' , type=int, help='port')
parser.add_argument('-t', dest='time' , type=int, help='Time (in seconds) to keep reading data from websocket. After this process will be exit. Default value is 0. For 0 it will run infinitely')
parser.add_argument('-m', dest='msg' , type=int, help='Number of message. Process will exit after receiving Number of messages. Default is 0, means runs for ever.')
args = parser.parse_args()
print(args.ip)
#ws://%s:%s" % (args.ip,args.port)
url = "ws://%s:%s" % (args.ip,args.port)
ws = create_connection(url)
print "Receiving data from the socket..."
tstart = time.time()
nbmsg = 0
for each in ws:
result = ws.recv();
nbmsg += 1
if args.time is not None:
if time.time() > tstart + args.time:
print('Time limit reached.')
sys.exit()
if args.msg is not None and nbmsg >= args.msg:
print('Message limit reached')
sys.exit()
print "Received '%s'" % result
ws.close();