为什么 format(str(var)) 给我 os.system 的属性错误

Why is format(str(var)) giving me an Attribute Error for my os.system

我正在尝试制作一个 Python 脚本,将我连接到 VPN 服务器 'number'(将此数字作为变量)

我写了:

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

在你提供的片段中,你写

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

您正在对 os.system 的 return 值进行 format 调用,该值恰好是一个整数。这等同于写成

5.format(args)

因为 int 对象没有属性 format,你得到你描述的 AttributeError

你要写的是

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

在此特定情况下,您的代码段应类似于

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

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