添加子进程时出错:变量未定义
我的脚本会接收一些参数,比如
C:\> python lookup.py "sender-ip=10.10.10.10"
然后它会获取发送者的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
1 个回答
1
这里不需要全局变量。只需在使用之前给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