Two ways to read a configuration file in Python

Source: Internet
Author: User
Tags in python

Configparser module is

The code is as follows Copy Code
#!/usr/bin/python

Import Configparser
CF = Configparser.configparser ()

If __name__== "__main__":
Cf.read (' test.conf ')
Tcpdumpnet = Cf.get ("Tcpdump_param", "Tcpdump_netdevice")
Tcpdumppro = Cf.get ("Tcpdump_param", "Tcpdump_protocol")

Sship = Cf.get ("Sshparam", "Remove_hostip")
Sshport = Cf.get ("Sshparam", "Remove_hostport")

Interval = Cf.get ("Otherparam", "Interval")
Under_value = Cf.get ("Otherparam", "Under_value")

Print Tcpdumpnet,tcpdumppro,sship,sshport,interval,under_value
~

Results

The code is as follows Copy Code

./configparser.py
Eth1 TCP 192.168.1.100 22 3 7

Sometimes configuration files need to be shared with shell programs

The code is as follows Copy Code

#!/usr/bin/python
Import re

Configfile=file (' test.conf ', ' R ')
For line in ConfigFile:
List=re.split (' s+|=+ ', line)
PARAM=LIST[0]
VALUE=LIST[1]
if (param== ' Tcpdump_protocol '):
Tcpdumppro=value
elif param = = ' Remove_hostip ':
Sship=value
elif param = = "Tcpdump_netdevice":
Tcpdumpnet=value
elif param = = "Remove_hostport":
Sshport=value
elif param = = "Interval":
Interval=value
elif param = = "Under_value":
Under_value=value
Print Tcpdumpnet,tcpdumppro,sship,sshport,interval,under_value

Results

The code is as follows Copy Code

./readconfigfile.py
Eth1 TCP 192.168.1.100 22 3 7

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.