【问题标题】:Python execfile print none, not print value from variablePython execfile不打印,不打印变量中的值
【发布时间】:2019-03-02 13:17:08
【问题描述】:

我有文件 mikrotik.py

'ip route add dst-address={}/{} gateway={}'.format(destination,prefix,gateway)

还有一些代码

import os
    localfilepath = os.getcwd()
    staticDir = localfilepath+"/website/plugin/config/routing/static/"
    vendors = staticDir+"MIKROTIK.py"
    destination = 192.168.2.0
    prefix = 24
    gateway = 192.168.1.1
    x = execfile(vendors)
    print x

结果是

None

我想要的结果是

ip route add dst-address=192.168.2.0/24 gateway=192.168.1.1

当我使用时

x = open(vendors)
print x

结果是

'ip route add dst-address={}/{} gateway={}'.format(destination,prefix,gateway)

提前致谢

所以最后我使用了 eval(x)

结果是 ip route add dst-address=192.168.2.0/24 gateway=192.168.1.1,我不知道这是不是最好的方法

【问题讨论】:

    标签: python networking execfile


    【解决方案1】:

    如果我理解正确,你只需要简单的字符串操作:

    import os
    
    destination = 192.168.2.0
    prefix = 24
    gateway = 192.168.1.1
    vendors = 'ip route add dst-address={}/{} gateway={}'.format(destination,prefix,gateway)
    print x
    

    如果您真的想将字符串/格式放在单独的文件中,请使用文本文件、json 文件等,但不要使用 .py 文件。

    顺便说一句,识别在python中很重要。

    【讨论】:

    • 所以如果我使用文本文件或 json 文件,我该怎么办
    • 假设一个文本文件有内容:ip route add dst-address={}/{} gateway={},在python sn-p中,将文本文件内容读入vendor_str,然后读入vendors=vendor_str.format(destination, prefix, gateway)。我不知道我为什么这样做:-)
    猜你喜欢
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    相关资源
    最近更新 更多