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

时间:2014-05-06 14:10:31

标签: python variables

我的脚本获取诸如

之类的参数
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

1 个答案:

答案 0 :(得分: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