Turn_On_or_Turn_Off_Firewall = "on" # give here "off" or "on"

from subprocess import Popen, PIPE

def ecmd(command):
    obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    return ret,out,err

if Turn_On_or_Turn_Off_Firewall.lower()=="on":
    command = "sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 1"
    message = "successfully turned on MacOS firewall"
elif Turn_On_or_Turn_Off_Firewall.lower()=="off":
    command = "sudo defaults write /Library/Preferences/com.apple.alf globalstate -int 0"
    message = "successfully turned off MacOS firewall"
else:
    raise Exception('please check the spelling of "off" or "on" that you have given in the variable "Turn_On_or_Turn_Off_Firewall"')

ret,out,err = ecmd(command)
if ret==0:
    if out:
        print(out.decode('utf-8').strip())
    print(message)
else:
    print(err.decode('utf-8').strip())