我试图用python创建一个程序,我最大的问题是让它使用命令行选项来分配程序中的变量。我一直在使用getopt,它将从我定义它的地方打印出来,但是不能在定义之外调用变量,这样我就可以在程序的其余部分使用它。在
在下面的代码中,“Is following correct”的打印状态很好,但是如果我试图在代码后面打印性别或任何其他变量,我只会得到一个错误,即它没有被定义。在
顺便说一下,我运行的选项是:spice.py -g m -n 012.345.6789 -r 23 -e 13 -o voicemail.mp3
代码:
import sys
import getopt
def main(argv):
gender = 'missing'
phone = 'missing'
reasons = 'missing'
endings = 'missing'
output = 'missing'
try:
opts, args = getopt.getopt(argv, "hg:n:r:e:o:")
except getopt.GetoptError:
print 'spice.py -g <gender> -n <phone number> -r <reasons> -e <endings> -o <output name>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-g"):
gender = arg
elif opt in ("-n"):
phone = arg
elif opt in ("-r"):
reasons = arg
elif opt in ("-e"):
endings = arg
elif opt in ("-o"):
output = arg
print "Is the following correct? " + "Gender: " + gender + ", " + "Phone Number: " + phone + ", " + "Reasons: " + reasons + ", " + "Endings: " + endings + ", " + "Output: " + output
if __name__ == "__main__":
main(sys.argv[1:])
print gender
在您的代码中,
gender
不是全局的。它只在函数的上下文中。在作为证明,将前几行改为:
现在您将看到它打印出来(假设它在您描述的上下文中工作)。在
当你重构的时候,你需要写一些函数来返回你想要使用的值,然后再使用它们,或者创建全局变量并稍微清理一下代码。在
相关问题 更多 >
编程相关推荐