簡體   English   中英

TypeError:只能將 str(不是“NoneType”)連接到 str,與 optparse 模塊一起使用

[英]TypeError: can only concatenate str (not "NoneType") to str, working with optparse module

import subprocess
import optparse

def change_mac(interface, new_mac):
    print("[+] Changing MAC address for " + interface + " to " + new_mac)

    subprocess.call(["ifconfig", interface, "down"])
    subprocess.call(["ifconfig", interface, "hw", "ether ", new_mac])
    subprocess.call(["ifconfig", interface, "up"])


parser = optparse.OptionParser()

parser.add_option( "-i", "--interface", dest="interface", help="interface to change its MAC address")
parser.add_option( "-m", "--mac", dest="new_mac", help="new MAC address")

(options, arguments) = parser.parse_args()
change_mac(options.interface, options.new_mac)

這是錯誤

Traceback (most recent call last):
  File "main.py", line 19, in <module>
    change_mac(options.interface, options.new_mac)
  File "main.py", line 7, in change_mac
    print("[+] Changing MAC address for " + interface + " to " + new_mac)
TypeError: can only concatenate str (not "NoneType") to str

我知道 Python 基礎知識,並且在此之前我做過一些程序,我正在學習一門課程,那個人制作了這個確切的程序,但他沒有出錯,我是。 如果有人可以幫助我理解問題,那將非常有幫助,因為我不想在不解決此問題的情況下進一步學習課程。

考慮為這些選項添加默認值:

parser.add_option( "-i", "--interface", dest="interface", help="interface to change its MAC address", default="interface not provided")
parser.add_option( "-m", "--mac", dest="new_mac", help="new MAC address", default="mac address not provided")

嘗試這個

def change_mac(interface, new_mac):
    interface = interface or '' # instead of empty string you can set a value
    new_mac = new_mac or '' # instead of empty string you can set a value
    print("[+] Changing MAC address for " , interface , " to " , new_mac)

或者您可以在方法的定義中使用默認值

def change_mac(interface='some_value', new_mac='Some Value'):
    print("[+] Changing MAC address for " , interface , " to " , new_mac)

嘗試:

import subprocess
import optparse

def change_mac(interface, new_mac):
    print("[+] Changing MAC address for " , interface , " to " , new_mac)

    subprocess.call(["ifconfig", interface, "down"])
    subprocess.call(["ifconfig", interface, "hw", "ether ", new_mac])
    subprocess.call(["ifconfig", interface, "up"])


parser = optparse.OptionParser()

parser.add_option( "-i", "--interface", dest="interface", help="interface to change 
its MAC address")
parser.add_option( "-m", "--mac", dest="new_mac", help="new MAC address")

(options, arguments) = parser.parse_args()
change_mac(options.interface, options.new_mac)

出現此錯誤的原因是,如果要添加兩個或多個字符串,則只能使用“+”。 但是 interface 和 new_mac 不是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM