python - 如何修复 subprocess.check_output() 的 None 返回值?
问题描述
我的代码使用子进程扫描路由器的 MAC 地址。但在启动时,它返回“无”。我怎样才能解决这个问题?
import re
import os
import subprocess
# MAC address regex
macRegex = re.compile("[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$")
cmd = "chcp 65001 && ipconfig | findstr /i \"Default Gateway\""
res = subprocess.check_output(cmd, shell=True, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
def GetMacByIP():
z = subprocess.check_output('arp -a ', shell=True, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
a = z.decode(encoding="cp866")
f = a.find("Physical Address")
o = a[f:].split(' ')
for a in o:
if macRegex.match(a):
return a.replace('-', ':')
解决方案
这部分在这里:
def GetMacByIP():
z = subprocess.check_output('arp -a ', shell=True, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
a = z.decode(encoding="cp866")
f = a.find("Physical Address")
o = a[f:].split(' ')
for a in o:
#print(a)
#print(macRegex.match(a))
if macRegex.match(a): # It's possible that this if statement never meets
return a.replace('-', ':')
你有一个if
声明。当条件从不满足语句时,你没有告诉 python 要返回什么,所以它返回None
.
推荐阅读
- c++ - 如何使用模板化 std::function 作为参数?
- d3.js - d3 对数刻度总是返回 NaN
- c# - Unity3D C# - 获取脚本的类型
- java - 了解创建的 StreamProcessor 实例的数量和流任务是否共享相同的流处理器实例?
- c - 函数声明隐藏全局声明
- r - R:根据另一列中存在的一列值生成一个虚拟变量
- javascript - python和javascript:如何从Flask服务器下载文件
- iterator - 如何提取增加的连续值?
- html - 当位置固定时,Bootstrap 4 巨型菜单下拉菜单不会留在容器内
- ruby - 如何修复“检测到不一致的缩进”