首页 > 解决方案 > 如何修复 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('-', ':')

标签: pythonregexsubprocess

解决方案


这部分在这里:

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.


推荐阅读