【问题标题】:Why is format(str(var)) giving me an Attribute Error for my os.system为什么 format(str(var)) 给我的 os.system 一个属性错误
【发布时间】:2020-02-08 16:20:51
【问题描述】:

我正在尝试制作一个 Python 脚本,将我连接到 VPN 服务器“号码”(将此号码作为变量)

我写道:

import os
VPNServer = 0
VPNServer += 1
os.system("networksetup -connectpppoeservice 'VPNServer {servernumber}'").format(servernumber = str(VPNServer))
print("→ Successfully connected to", "VPNServer", VPNServer)

但每次我尝试运行它时,控制台都会给我一个 AttributeError

AttributeError: 'int' object has no attribute 'format'

看不懂,因为我取了变量的字符串版本

如果有人可以帮忙,那就太棒了

我在 macOS 上使用 Python 3.8.1

【问题讨论】:

    标签: python macos attributeerror os.system


    【解决方案1】:

    在你提供的 sn-p 中,你写

    os.system('<some string>').format(args)
    

    您正在对os.system 的返回值进行format 调用,该值恰好是一个整数。这与写作相同,例如

    5.format(args)
    

    由于int 对象没有format 属性,因此您将得到您所描述的AttributeError

    你要写的是

    os.system('<some string>'.format(args))
    

    在这种特定情况下,您的 sn-p 应该类似于

    os.system(
        "networksetup -connectpppoeservice 'VPNServer {servernumber}'"
           .format(servernumber=VPNServer)
    )
    

    注意str(VPNServer) 调用是多余的,因为format 会自动调用所提供对象的__str__ 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2022-01-05
      • 1970-01-01
      • 2018-12-23
      • 2017-12-17
      相关资源
      最近更新 更多