如何使用用户inpu将文件中的特定变量传递给另一个变量

2024-09-29 23:25:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个配置网络接口的功能。 它向用户请求新的IP地址/netmask/gateway/和DNS,并将新值写入/etc/network/interfaces文件: 在写入文件之前,我有另一个名为“vaildIP”的函数,它检查用户输入的IP地址是否正确,然后将新值传递给interfaces文件。你知道吗

address = vaildIP ('Address[current value is <no-value>:')
netmask = vaildIP('Netmask[current value is < no - value >]:')
gateway = vaildIP('Gateway[current value is < no - value >]:')
dns = raw_input('DNS servers [current value is <no-value>]:') or "8.8.8.8"

所以我的问题是如何读取/etc/network/interfaces文件并将当前值添加到另一个没有值的变量中

例如,它应该是:

现在是:没有价值

address = vaildIP ('Address[current value is <no-value>:')

我希望是:

address = vaildIP ('Address[current value is 192.168.1.34:') * or any other ip

到目前为止,我设法打开文件并打印值,但我无法将值传递到其no-value所在的位置:

with open("/etc/network/interfaces", "r+") as file:
     file_content = file.readlines()
     for line in file_content:
        if line.startswith("address") or line.startswith("netmask") or line.startswith("gateway") or line.startswith("dns-nameservers"):
            print 'current values are -- {lineip}'.format(lineip = line)

有人能帮我弄清楚吗


Tags: or文件noisvalueaddresslineetc
1条回答
网友
1楼 · 发布于 2024-09-29 23:25:44
#variables to store info available in /etc/network/interfaces file
    address_value = '<no-value>'
    netmask_value = '<no-value>'
    gateway_value = '<no-value>'
    dns_value = '<no-value>'

    with open("/Users/yossi.s/Desktop/interfaces.txt", "r+") as file:
     file_content = file.readlines()

     #read data from /etc/network/interfaces and store in variables
     for line in file_content:
        if line.startswith("address"):
            address_value = line.strip()
        elif line.startswith("netmask"):
            netmask_value = line.strip()
        elif line.startswith("gateway"):
            gateway_value = line.strip()
        elif line.startswith("dns-nameservers"):
            dns_value = line.strip()

    address = vaildIP ('Address[current value is {val}]:'.format(val=address_value))
    netmask = vaildIP('Netmask[current value is {val}]:'.format(val=netmask_value))
    gateway = vaildIP('Gateway[current value is {val}]:'.format(val=gateway_value))
    print "[Network Interface] Please provide the DNS servers to use (one or more, separated with spaces), \n  or press Enter `enter code here`to use the existing value."
    dns = raw_input('DNS servers [current value is {val}]:'.format(val=dns_value)) or "8.8.8.8"

相关问题 更多 >

    热门问题