Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:+;的操作数类型不受支持:';非类型';和';str'+;主办_Python - Fatal编程技术网

Python TypeError:+;的操作数类型不受支持:';非类型';和';str'+;主办

Python TypeError:+;的操作数类型不受支持:';非类型';和';str'+;主办,python,Python,我对编程非常陌生,我发现了这个程序并应用了它,但我发现了这些错误(我把错误放在程序末尾), 导入请求 导入telnetlib 导入时间 导入系统 import numpy as np import matplotlib import matplotlib.patches as mpatches import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.ticker as p

我对编程非常陌生,我发现了这个程序并应用了它,但我发现了这些错误(我把错误放在程序末尾), 导入请求 导入telnetlib 导入时间 导入系统

import numpy as np
import matplotlib
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.ticker as plticker

USERNAME = 'ubnt'
PASSWORD = 'ubnt1'
HOST = "192.168.1.220"
PORT = 18888
TIMEOUT = 10
FRAME_SPEED = 1

LOGIN_URI = 'http://' + HOST + ':80/login.cgi'
#LOGIN_URI = 'https://' + HOST + ':443/login.cgi'

def usage():
 print ("Usage:+ sys.argv[0] +  <live|replay FILENAME>")
print ("")
print ("Options:")
print ("\tlive              \t=\tProcess live data from device ") + HOST
print ("\treplay FILENAME   \t=\tReplay FILENAME")
print ("\trecord FILENAME   \t=\tMake movie of FILENAME")
exit(128)

if len(sys.argv) == 2 and sys.argv[1] == 'live':
ACTION='live'
FILENAME = None
elif len(sys.argv) == 3 and sys.argv[1] == 'replay':
ACTION='replay'

ocessing
FRAME_SPEED = 50
elif len(sys.argv) == 3 and sys.argv[1] == 'record':
ACTION='record'
FILENAME = sys.argv[2] # Stored data processing
FRAME_SPEED = 50
else:
usage()



def parse_get_frame_resp(line):
_,vals_raw = line.split(':')
vals = map(int, vals_raw.split(','))
frame_nr = vals.pop(0)
return(frame_nr, vals)

#TODO: Make me dynamic parse from 'SCAN RANGE' response
scan_range_begin = 2402000000
scan_range_end = 2497000000

if not FILENAME:
print ("Enabling Ubiquiti airView at %s:%s@%s...") %(USERNAME, PASSWORD, HOST)
s = requests.session()
s.get(LOGIN_URI, verify=False)
r = s.post(LOGIN_URI,
    {"username": USERNAME, "password": PASSWORD, "uri": "airview.cgi?   start=1"},
    verify=False)
 if 'Invalid credentials.' in r.text:
    print ("# CRIT: Username/password invalid!")
    sys.exit(1)
print ("Waiting for device to enter airView modus...")
# Allow device a few moments to settle
time.sleep(TIMEOUT)

print ("Start scanning...")
tn = telnetlib.Telnet(HOST, PORT, timeout=TIMEOUT)
#tn.set_debuglevel(99)

# Storage on unique files
outfile = 'output-%s.dat' % int(time.time())
print ("Storing output at '%s'") % outfile
fh = open(outfile, 'a')
def writeline(cmd):
    """ Write line to device"""
    ts = time.time()
    tn.write(cmd)
    print (cmd) 
    fh.write("%s\001%s" % (ts, cmd))
    return ts


def getline():
    """Read line from device"""
    line = tn.read_until("\n")
    print (line)
    fh.write("%s\001%s" % (time.time(), line))
    return line

# Commands needs to have a trailing space if no arguments specified
writeline("CONNECT: \n")
getline()

#writeline("REQUEST RANGE: 2402000000,2407000000\n") #  5 MHz
#writeline("REQUEST RANGE: 2402000000,2412000000\n") # 10 MHz
#writeline("REQUEST RANGE: 2402000000,2417000000\n") # 15 MHz
#writeline("REQUEST RANGE: 2402000000,2422000000\n") # 20 Mhz
#writeline("REQUEST RANGE: 2402000000,2477000000\n") # (ch 1-11 - US   allocation)
#writeline("REQUEST RANGE: 2402000000,2487000000\n") # (ch 1-13 - UK allocation)
writeline("REQUEST RANGE: 2402000000,2497000000\n") # (ch 1-14)
getline()

writeline("START SCAN: \n")
getline()
print ("Waiting for scan to start...")
time.sleep(2)

def get_frame(frame):
    """ Get frame from device airView """
    # TODO: Receiving frames in order, sometimes yield of empty responses.              Already flush out maybe?
    #writeline("GET FRAME: %s\n" % frame)
    ts = writeline("GET FRAME: \n")
    line = getline()
    return((ts,) + parse_get_frame_resp(line))
else:
# No need for logic since we are processing stored data
sh = open(FILENAME, 'r')
def get_frame(frame):
    """ Perform replay data processing """
    while True:
        line = sh.readline()
        if not line:
            return(None, None, None)
        ts_raw, a = line.split('\001', 1)
        ts = float(ts_raw)
        cmd, ret = a.split(':', 1)
        if cmd == 'FRAME':
            return((ts,) + parse_get_frame_resp(a))


 # Get innitial frame number and bins sizes
_, frame_nr, vals = get_frame(None)
bin_size = len(vals)
bin_sample_khz = float(scan_range_end - scan_range_begin) / 1000 / bin_size
print ("Bin size: %s") % bin_size


# Start making picture
fig, ax = plt.subplots(figsize=(20,11))
fig.canvas.set_window_title('UBNT airView Client')
ax.set_ylabel('100ms units elapsed')
ax.set_xlabel('Frequency (sampled with bins of %s kHz)' % bin_sample_khz)

# Channel center frequencies
a =    [2402,2412,2417,2422,2427,2432,2437,2442,2447,2452,2457,2462,2467,2472,2484,2497]
channels = (np.array(a,dtype='float32') - 2402) / (bin_sample_khz / 1000)
ax.get_xaxis().set_ticks(channels)
plt.xticks(rotation=90)

# Plot channel description
for i in range(1,15):
width_20mhz = 20000.0 / bin_sample_khz
if i in [1,6,11,14]:
    pac = mpatches.Arc([channels[i], 0], width_20mhz, 300, 
        theta2=180, linestyle='solid', linewidth=2, color='black')
else:
    pac = mpatches.Arc([channels[i], 0], width_20mhz, 300, 
        theta2=180, linestyle='dashed', linewidth=2, color='black')
ax.add_patch(pac)


ax.get_xaxis().set_major_formatter(
plticker.FuncFormatter(lambda x, p: format(int((x * bin_sample_khz / 1000) +  2402), ',')))

plt.grid(linewidth=2,linestyle='solid',color='black')
plt.tight_layout()

bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width*fig.dpi, bbox.height*fig.dpi
print (width), (height)

# Initial data and history of amount of pixels of the screen, since it is
# important that all lines are draw on the screen.
bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width*fig.dpi, bbox.height*fig.dpi

matrix = np.empty([int(height),bin_size]) * np.nan
pcm = ax.pcolorfast(matrix, vmin=-122, vmax=-30)

if ACTION == 'record':
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='AnyWi UBNT airViewer'),    bitrate=1800)

#
# Matplotlib Animation
#
def update(data):
global frame_nr, matrix

# Fast forwarding in time
for i in range(FRAME_SPEED):

    frame_nr_next = -1

    # The same frame (duplicated), we are too fast
    while frame_nr_next <= frame_nr:
        ts, frame_nr_next, row = get_frame(frame_nr + 1)

    frame_nr = frame_nr_next

    # We are on the end of the file
    if not ts and not frame_nr and not row:
        return

    #matrix = np.vstack([row, pcm.get_array()[:-1]])
    matrix = np.vstack([row, matrix[:-1]])

pcm.set_array(matrix)
ax.set_title('Frame %s at %s' % (frame_nr,time.asctime(time.localtime(ts))))     
#fig.canvas.draw()


ani = animation.FuncAnimation(fig, update, interval=100)

# Dual display and recording data does not seems to work, use a screencast
# program like gtk-recordmydesktop for that matter
if ACTION == 'record':
ani.save('live.mp4' if not FILENAME else FILENAME.rsplit('.',1)[0] + '.mp4',  writer=writer)
else:
plt.show()

#
# Takes some time (10 seconds) for device to return to an active state
#


error output
Usage:+ sys.argv[0] +  <live|replay FILENAME>

Options:
live                =   Process live data from device 
Traceback (most recent call last):
File "C:\Users\ABDULHUSSEIN\Desktop\py-ubnt-airviewer-master\airviewer.py",                                            line 76, in <module>
usage()
File "C:\Users\ABDULHUSSEIN\Desktop\py-ubnt-airviewer-master\airviewer.py",    line 58, in usage
print ("\tlive              \t=\tProcess live data from device ") + HOST
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
将numpy导入为np
导入matplotlib
将matplotlib.patches作为MPatch导入
将matplotlib.pyplot作为plt导入
将matplotlib.animation导入为动画
将matplotlib.ticker导入为plticker
用户名='ubnt'
密码='ubnt1'
HOST=“192.168.1.220”
端口=18888
超时=10
帧速度=1
LOGIN_URI='http://'+HOST+':80/LOGIN.cgi'
#LOGIN_URI='https://'+HOST+':443/LOGIN.cgi'
def用法():
打印(“用法:+sys.argv[0]+”)
打印(“”)
打印(“选项:”)
打印(“\tlive\t=\t从设备处理实时数据”)+主机
打印(“\t播放文件名\t=\t播放文件名”)
打印(“\t记录文件名\t=\t制作文件名的电影”)
出口(128)
如果len(sys.argv)==2和sys.argv[1]=='live':
现场直播
文件名=无
elif len(sys.argv)==3和sys.argv[1]=='replay':
“重播”行动
加工
帧速度=50
elif len(sys.argv)==3和sys.argv[1]=='record':
行动记录
FILENAME=sys.argv[2]#存储数据处理
帧速度=50
其他:
用法()
def parse_get_frame_resp(行):
_,vals_raw=line.split(“:”)
VAL=map(整数,VAL_原始分割(','))
帧编号=VAL.pop(0)
返回(帧号,VAL)
#TODO:从“扫描范围”响应进行动态解析
扫描范围开始=2402000000
扫描范围=2497000000
如果不是文件名:
打印(“在%s启用泛素airView:%s@%s…”)(用户名、密码、主机)
s=请求。会话()
s、 获取(登录URI,验证=False)
r=s.post(登录URI,
{“用户名”:用户名,“密码”:密码,“uri”:“airview.cgi?start=1”},
验证(错误)
如果r.text中的“无效凭据”:
打印(“CRIT:Username/password无效!”)
系统出口(1)
打印(“等待设备进入airView modus…”)
#让设备静置片刻
时间。睡眠(超时)
打印(“开始扫描…”)
tn=telnetlib.Telnet(主机、端口、超时=超时)
#tn.set_调试级别(99)
#唯一文件上的存储
outfile='输出-%s.dat'%int(time.time())
打印(“在“%s”处存储输出)%outfile
fh=打开(输出文件“a”)
def写线(cmd):
“”“将行写入设备”“”
ts=时间。时间()
tn.write(cmd)
打印(cmd)
fh.写入(“%s\001%s”%(ts,cmd))
返回ts
def getline():
“”“从设备读取行”“”
行=tn.read_直到(“\n”)
打印(行)
fh.write(“%s\001%s”%(time.time(),第行))
回程线
#如果未指定参数,则命令需要有尾随空格
writeline(“连接:\n”)
getline()
#writeline(“请求范围:240200002407000000\n”)#5 MHz
#writeline(“请求范围:2402000002412000000\n”)#10 MHz
#写入线(“请求范围:24020000024700000\n”)#15 MHz
#写线(“请求范围:240200000242000000\n”)#20 Mhz
#writeline(“请求范围:2402000002477000000\n”)#(第1-11章-美国分配)
#writeline(“请求范围:2402000002487000000\n”)#(第1-13章-英国分配)
写线(“请求范围:2402000002497000000\n”)#(第1-14章)
getline()
writeline(“开始扫描:\n”)
getline()
打印(“等待扫描开始…”)
时间。睡眠(2)
def get_帧(帧):
“”“从设备airView获取帧”“”
#TODO:按顺序接收帧,有时会产生空响应。可能已经冲出来了?
#writeline(“获取帧:%s\n”%FRAME)
ts=writeline(“获取帧:\n”)
line=getline()
返回((ts,)+parse\u get\u frame\u resp(line))
其他:
#不需要逻辑,因为我们正在处理存储的数据
sh=打开(文件名“r”)
def get_帧(帧):
“”“执行重播数据处理”“”
尽管如此:
line=sh.readline()
如果不是直线:
返回(无,无,无)
ts_raw,a=line.split('\001',1)
ts=浮动(ts_原始)
cmd,ret=a.split(“:”,1)
如果cmd=='FRAME':
返回((ts,)+parse\u get\u frame\u resp(a))
#获取初始帧编号和箱子大小
_,帧编号,VAL=获取帧(无)
箱柜尺寸=长度(VAL)
bin\u样本\u khz=浮动(扫描范围\u结束-扫描范围\u开始)/1000/bin\u大小
打印(“仓位大小:%s”)%Bin\u大小
#开始画画
图,ax=plt.子批次(图尺寸=(20,11))
图画布设置窗口标题(“UBNT airView客户端”)
ax.set_ylabel('100ms单位运行时间')
ax.设置标签('频率(以%s kHz的间隔采样)'%bin\u采样间隔kHz)
#信道中心频率
a=[2402241224172422242724322437244224472452245724622467247842497]
通道=(np.array(a,dtype='float32')-2402)/(bin_sample_khz/1000)
ax.get_xaxis().set_刻度(通道)
plt.xticks(旋转=90)
#打印通道描述
对于范围(1,15)内的i:
宽度\u 20mhz=20000.0/bin\u样本\u khz
如果我在[1,6,11,14]中:
pac=mpatches.Arc([通道[i],0],宽度_20mhz,300,
theta2=180,线型为“实心”,线宽为2,颜色为“黑色”)
其他:
pac=mpatches.Arc([通道[i],0],宽度_20mhz,300,
θ=180,线型为“虚线”,线宽为2,颜色为“黑色”)
ax.添加补丁(pac)
ax.get_xaxis().set_major_格式化程序(
plticker.FuncFormatter(lambda x,p:format(int((x*bin_sample_khz/1000)+2402),','))
plt.grid(线宽=2,线型=实心,颜色=黑色)
plt.紧_布局()
bbox=图get_window_extent().转换(图dpi_scale_trans.倒置())
宽度,高度=bbox.width*fig.dpi,bbox.height*fig.dpi
打印(宽度),(高度)
#屏幕像素量的初始数据和历史记录,因为它是
#在屏幕上绘制所有线条非常重要。
bbox=图get_window_extent().转换(图dpi_scale_trans.倒置())
宽度,高度=bbox.width*fig.dpi,bbox.height*fig.dpi
矩阵=np.空([int(高度),bin_大小])*np.nan
pcm=ax.pcolorfast(矩阵,vmin=-122,vmax=-30)
如果操作==‘记录’:
#设置电影文件的格式
Writer=动画。writers['ffmpeg']
writer=writer(fps=15,metadata=dict(artist='AnyWi-UBNT-airViewer'),