我想将我的默认网关保存在一个变量中,以备将来使用,比如打印它,或者向它发送一个ping……我希望代码可以在Windows和Linux上运行,所以我编写了以下代码:
import os
if os.name == "Linux":
dgw = os.system('ip r | grep default | awk {"print $3"}')
print dgw
if os.name == "Windows":
dgw = os.system('ifconfig | findstr /i "Gateway"')
print dgw
但是dgw变量并没有保存我的默认网关...
python 2.7
发布于 2018-12-23 18:07:27
首先,Windows下的os.name
是'nt'
,Linux上的是'posix'
。
这也会在documentation中突出显示
导入的操作系统相关模块的名称。当前已注册以下名称:'posix‘、'nt’、'java‘。
如果您想针对更具体的平台,使用sys.platform
是更好的选择。
其次,使用netifaces
模块可以很好地在Windows和Linux上运行:
import netifaces
gateways = netifaces.gateways()
default_gateway = gateways['default'][netifaces.AF_INET][0]
print(default_gateway)
它可以与pip install netifaces
一起安装。这种方法的好处是,您不需要区分Windows和Linux的方法。
发布于 2018-12-23 17:47:20
这是因为os.system不返回标准输出。你应该使用子进程。
#For Linux
import subprocess
p = subprocess.Popen(["ip r"], stdout=subprocess.PIPE, shell=True)
out = p.stdout.read()
print out
https://stackoverflow.com/questions/53902519
复制相似问题