Search code examples
pythonmacosattributeerroros.system

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


I'm trying to make a Python script that connects me to a VPN Server 'number' (with this number as a variable)

I wrote:

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

But everytime I try to run it, the console gives me an AttributeError

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

I don't understand it because I took the string version of the variable

If someone could help, it would be super cool

I'm on macOS and I'm using Python 3.8.1


Solution

  • In the snippet you provided, you write

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

    You are making the format call on the return value of os.system, which happens to be an integer. This is identical to writing e.g.

    5.format(args)
    

    Since int objects have no attribute format, you get the AttributeError you described.

    What you want to write is

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

    In this specific case, your snippet should resemble

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

    Note that the str(VPNServer) call is superfluous, since format will autmatically call the __str__ method of the object provided.