if __name__ == '__main__': main()出现了 with open(config_file_env, 'r') as stream: TypeError: expected str, bytes or os.PathLike object, not NoneType这个错误
时间: 2023-07-21 07:23:18 浏览: 135
这个错误通常是因为你使用了一个空的配置文件路径。导致 `config_file_env` 变量为 `NoneType`。你需要在调用 `open()` 函数之前检查一下 `config_file_env` 是否为 `None`。
例如,你可以这样检查:
```python
if config_file_env is not None:
with open(config_file_env, 'r') as stream:
# 你的代码
else:
print("配置文件路径为空!")
```
这样,如果 `config_file_env` 为空,你就可以避免使用 `open()` 函数,从而避免这个错误。
相关问题
#!/usr/bin/env python #coding: utf-8 import os from time import time from datetime import datetime from netmiko import ConnectHandler from openpyxl import Workbook from openpyxl import load_workbook def read_device_excel( ): ip_list = [] wb1 = load_workbook('E:\/Users/Wayne_Peng/Desktop/cs_lab.xlsx') ws1 = wb1.get_sheet_by_name("Sheet1") for cow_num in range(2,ws1.max_row+1): ipaddr = ws1["a"+str(cow_num)].value ip_list.append(ipaddr) return ip_list def get_config(ipaddr): session = ConnectHandler(device_type="huawei", ip=ipaddr, username="mtlops", password="cisco,123", banner_timeout=300) print("connecting to "+ ipaddr) print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr)) # config_data = session.send_command('screen-length 0 temporary') # config_data = session.send_command('dis cu | no-more ') # command = 'display version | display cpu-usage | display memory-usage' # config_data = session.send_command(command) commands = ['display version', 'display cpu-usage', 'display memory-usage'] config_data = '' for cmd in commands: output = session.send_command_timing(cmd) config_data += f'{cmd}\n{output}\n' session.disconnect() return config_data def write_config_to_file(config_data,ipaddr): now = datetime.now() date= "%s-%s-%s"%(now.year,now.month,now.day) time_now = "%s-%s"%(now.hour,now.minute) #---- Write out configuration information to file config_path = 'E:\/Users/Wayne_Peng/Desktop/' +date verify_path = os.path.exists(config_path) if not verify_path: os.makedirs(config_path) config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name print ('---- Writing configuration: ', config_filename) with open( config_filename, "w",encoding='utf-8' ) as config_out: config_out.write( config_data ) return def main(): starting_time = time() ip_list = read_device_excel() for ipaddr in ip_list: hwconfig = get_config(ipaddr) write_config_to_file(hwconfig,ipaddr) print ('\n---- End get config threading, elapsed time=', time() - starting_time) #======================================== # Get config of HUAWEI #======================================== if __name__ == '__main__': main() 加一段gevent,def run_gevent()
好的,可以尝试这样写:
```
#!/usr/bin/env python
#coding: utf-8
import os
from time import time
from datetime import datetime
from netmiko import ConnectHandler
from openpyxl import Workbook
from openpyxl import load_workbook
import gevent
from gevent import monkey
monkey.patch_all()
def read_device_excel():
ip_list = []
wb1 = load_workbook('E:\/Users/Wayne_Peng/Desktop/cs_lab.xlsx')
ws1 = wb1.get_sheet_by_name("Sheet1")
for cow_num in range(2,ws1.max_row+1):
ipaddr = ws1["a"+str(cow_num)].value
ip_list.append(ipaddr)
return ip_list
def get_config(ipaddr):
session = ConnectHandler(device_type="huawei",
ip=ipaddr,
username="mtlops",
password="cisco,123",
banner_timeout=300)
print("connecting to "+ ipaddr)
print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr))
commands = ['display version', 'display cpu-usage', 'display memory-usage']
config_data = ''
for cmd in commands:
output = session.send_command_timing(cmd)
config_data += f'{cmd}\n{output}\n'
session.disconnect()
return config_data
def write_config_to_file(config_data,ipaddr):
now = datetime.now()
date= "%s-%s-%s"%(now.year,now.month,now.day)
time_now = "%s-%s"%(now.hour,now.minute)
#---- Write out configuration information to file
config_path = 'E:\/Users/Wayne_Peng/Desktop/' +date
verify_path = os.path.exists(config_path)
if not verify_path:
os.makedirs(config_path)
config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name
print ('---- Writing configuration: ', config_filename)
with open( config_filename, "w",encoding='utf-8' ) as config_out:
config_out.write( config_data )
return
def run_gevent(ip_list):
jobs = []
for ipaddr in ip_list:
jobs.append(gevent.spawn(get_config, ipaddr))
gevent.joinall(jobs)
for job, ipaddr in zip(jobs, ip_list):
hwconfig = job.value
write_config_to_file(hwconfig,ipaddr)
print('\n---- End get config threading')
def main():
starting_time = time()
ip_list = read_device_excel()
run_gevent(ip_list)
print('elapsed time:', time() - starting_time)
#========================================
# Get config of HUAWEI
#========================================
if __name__ == '__main__':
main()
```
注意,这里使用了 `gevent` 库,需要先安装。可以在命令行中使用 `pip install gevent` 进行安装。
// >>> common include #include <iostream> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> // >>> verilator #include <memory> #include <verilated.h> #include <verilated_vcd_c.h> #include "VA_top.h" #include "sdm_config.h" #include "Sdm_node_A.h" using HW =VA_top; uint64_t GlobalMainTime = 0; int main(int argc, char** argv, char**env) { const std::unique_ptr<VerilatedContext> contextp{new VerilatedContext}; const std::unique_ptr<HW> hw {new HW{contextp.get(), "TOP"}}; Sdm_config * shuncfg_ptr = new Sdm_config (sub_node_A_node_name); shuncfg_ptr->arg_parse (argc, argv); Sdm_node_A shunobj (shuncfg_ptr, hw.get(), contextp.get()); Verilated::mkdir("node_node_A_logs"); contextp->debug(0); contextp->randReset(2); contextp->commandArgs(argc, argv); #if VM_TRACE == 1 VerilatedVcdC* tgp = NULL; const char* flag = Verilated::commandArgsPlusMatch("trace"); if (flag && 0 ==strcmp(flag, "+trace")) { Info("Enter Trace!"); contextp->traceEverOn(true); tfp = new VerilatedVcdC; hw->trace(tfp,99); shunobj.fulleval(); std::string filename = shuncfg_ptr->dumpfile(); tfp->open(filename.c_str()); }; #endif shunobj.setup(); bool retmp; int loop = 0; while(1) { //Info("loop %d", loop); shunobj.update(); if (shunobj.finish()) break; do { shunobj.eval(); shunobj.sync(); } while(!shunobj.converge()); #if VM_TRACE == 1 if (flag && 0 == strcmp(flag, "+trace")) { tfp->dump(contextp->time()); } #endif loop++; } hw->final(); return 0; #if VM_TRACE == 1 if (flag && 0 == strcmp(flag, "+trace")){ tfp->close(); } #endif #if VM_COVERAGE Verilated::mkdir("node_node_A_logs"); contextp->coverageep()->write("node_node_A_logs/coverage.dat"); #endif }
这是一个C++程序的主函数,它使用Verilator来模拟硬件电路。程序的作用是模拟一个名为"Sdm_node_A"的硬件节点,并根据节点的配置进行操作。
程序的主要流程如下:
1. 创建VerilatedContext和Verilated块的实例。
2. 解析命令行参数并配置Sdm_config。
3. 创建Sdm_node_A的实例,并传入配置、Verilated模块和VerilatedContext。
4. 创建用于存储仿真结果的文件夹,并设置调试和随机复位。
5. 如果编译时开启了跟踪功能(VM_TRACE == 1),则创建VerilatedVcdC实例,并根据配置打开跟踪文件。
6. 进行节点的初始化设置。
7. 进入主循环,更新节点状态,直到节点完成工作。
8. 在循环中,进行节点的评估和同步操作。
9. 如果编译时开启了跟踪功能,则在每个时钟周期将状态写入跟踪文件。
10. 最后进行清理和关闭跟踪文件(如果已打开)。
请注意,这段代码可能缺少一些定义和头文件的引用,例如"Info"函数的定义以及一些宏定义。在编译和运行代码之前,你需要确保所有的声明和定义都是正确的,并且所有的依赖项都已正确引入。如果需要更多帮助,请提供更多相关代码或详细说明。
阅读全文