我有一个相当简单的问题。我是python的新手,我试图在for循环中初始化一个变量,但我不希望在for循环中执行处理该变量的代码。
try:
opts, args = getopt.getopt(sys.argv[1:], "p:", ["PORT="])
print "getopt called"
except getopt.GetoptError:
print "getopt: error has occured"
sys.exit(2)
for opt, arg in opts:
if opt in ("-p", "--PORT"):
print "Using TCP port#: " , arg
TCP_PORT = arg ###<===== Trying to initialize TCP_PORT
socket.connect((TCP_IP, TCP_PORT)) ###<====== TCP_PORT used here
我知道在java中,你可以使用class.variable来访问你正在使用的范围之外的东西,无论如何在python中实现这一点?提前谢谢!
编辑:
运行时我得到以下输出:
python cli.py 5003
Traceback (most recent call last):
File "cli.py", line 25, in <module>
s.connect((TCP_IP, TCP_PORT))
NameError: name 'TCP_PORT' is not defined