我正在尝试编写一个 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
最佳答案
在您提供的代码片段中,您编写
os.system('<some string>').format(args)
您正在对 os.system
的返回值进行 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__
方法。
关于python - 为什么 format(str(var)) 给我的 os.system 属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60128706/