添加了子进程,错误提示变量未定义



我的脚本得到如下参数

C:> python lookup.py "sender-ip=10.10.10.10"

然后取sender-ip查找wmi信息

现在我在尝试获取wmi信息之前添加了一个ping子进程来检测机器,我得到以下错误

C:> python lookup.py "sender-ip=10.10.10.10"
Traceback (most recent call last):
  File "lookup.py", line 10, in <module>
    ["ping", "-n", "1", userIP],
NameError: name 'userIP' is not defined

然后我尝试在程序开始时定义userIP全局变量,但是我得到错误

C:> python lookup.py "sender-ip=10.10.10.10"
Traceback (most recent call last):
  File "lookup.py", line 10, in <module>
    ["ping", "-n", "1", userIP],
NameError: global name 'userIP' is not defined

下面是程序(没有全局声明)

# import statements
import sys, wmi, subprocess
# subprocess
ping = subprocess.Popen(
    ["ping", "-n", "1", userIP],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)
# get the arguments and extract user's IP address
argument = sys.argv[1]
attr_map = dict(item.strip().split('=') for item in argument.split(','))
userIP =  attr_map['sender-ip']
print userIP
# can we ping the user's IP address?
out, error = ping.communicate()
# if we cannot ping user's IP address then print error message and exit program
if out.find("Reply from") == -1:
    print userIP, "is NOT pingable."
    sys.exit()
# remaining lines will execute if we can ping user's IP address
c = wmi.WMI(userIP)
for os in c.Win32_OperatingSystem():
  print os.Caption

这里不需要全局变量。在使用userIP之前给它赋值:

# import statements
import sys, wmi, subprocess
# get the arguments and extract user's IP address
argument = sys.argv[1]
attr_map = dict(item.strip().split('=') for item in argument.split(','))
userIP =  attr_map['sender-ip']
print userIP
# subprocess
ping = subprocess.Popen(
    ["ping", "-n", "1", userIP],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)
# can we ping the user's IP address?
out, error = ping.communicate()
# if we cannot ping user's IP address then print error message and exit program
if out.find("Reply from") == -1:
    print userIP, "is NOT pingable."
    sys.exit()
# remaining lines will execute if we can ping user's IP address
c = wmi.WMI(userIP)
for os in c.Win32_OperatingSystem():
  print os.Caption

最新更新