TCL/Expect读取配置文件内容

本文介绍了一个使用expect脚本来解析config.xml配置文件的方法。该脚本能够逐行读取文件内容并根据指定的键(如password)来获取对应的值。通过此方式可以实现对配置文件中特定信息的自动化读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

config.xml配置文件如下:------------------------------------------------

name=tester ;#用户名

password=vmkid ;#密码


common.exp脚本如下:---------------------------------------------------

#!/usr/bin/expect

proc getConfig {configFile Key {Comment "#"} {Equal "="}} {    ;#过程中如果参数有缺省值,使用花括号引起,并赋值 
  set Value ""                   ;# 记录过程返回的值   
  # 打开配置文件 
  set err [catch {set fileid [open $configFile r]} errMsg] 
  if {$err == 1} { 
    puts "errMsg : $errMsg" 
    return $Value 
  } 
  # 成功打开文件后, 一行一行的加以分析 
  set rowid 0                       ;#记录当前行数,程序调试时打印调试信息使用的 
  while {[eof $fileid] != 1} {                 ;# 读取文件内容 
    incr rowid                          ;# 记录行数, 从一开始 
    gets $fileid line     ;# 读出一行 
    # 先去掉注释, 再去掉两端的空格 
    set commentpos [string first $Comment $line]        ;# 得到注释符号的位置 
    if { $commentpos != 0 } { 

      # 行以注释符号开头,忽略掉该行 
  } else { 
   if { $commentpos != -1 } {        ;# 行中有注释符号,去掉注释 
    set line [string range $line 0 [expr $commentpos-1]] 
   } 
   set line [string trim $line]          ;# 去掉两端的空格 
   # puts "$rowid : line : $line" 
   # 如果是空就继续循环 
   if { $line == "" } { 
    continue 
    } else {
    set equalpos [string first $Equal $line]   ;# 得到等号的位置 
    if { $equalpos != -1} { 
      # 如果就是找寻的key,结束循环 
     if { [string range $line 0 [expr $equalpos - 1]] == $Key } { 
      set Value [string range $line [expr $equalpos + 1] [string length $line]] 
      break 
     } 
    }
   } 
  } 
 } 
 # 关闭文件 
 close $fileid 

 #返回值
 return $Value 
} 

set val [getConfig "config.xml" "password"] 
puts "---------val: $val"

exit
expect eof

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值