[英]how to pass arguments to a module in python 2.x interactive mode
I'm using Python 2.7, and I have the following simple script, which expects one command line argument: 我正在使用Python 2.7,我有以下简单的脚本,它需要一个命令行参数:
#!/usr/bin/env python
import sys
if (len(sys.argv) == 2):
print "Thanks for passing ", sys.argv[1]
else:
print "Oops."
I can do something like this from the command line: 我可以从命令行执行以下操作:
My-Box:~/$ ./useArg.py asdfkjlasdjfdsa
Thanks for passing asdfkjlasdjfdsa
or this: 或这个:
My-Box:~/$ ./useArg.py
Oops.
I would like to do something similar from the interactive editor: 我想通过交互式编辑器做类似的事情:
>>> import useArg asdfasdf
File "<stdin>", line 1
import useArg asdfasdf
^
SyntaxError: invalid syntax
but I don't know how. 但我不知道怎么做。 How can I pass a parameters to import/reload in the interactive editor ?
如何在交互式编辑器中传递参数以导入/重新加载?
You can't. 你不能。 Wrap your code inside the function
将代码包装在函数中
#!/usr/bin/env python
import sys
def main(args):
if (len(args) == 2):
print "Thanks for passing ", args[1]
else:
print "Oops."
if __name__ == '__main__':
main(sys.argv)
If you execute your script from command line you can do it like before, if you want to use it from interpreter: 如果您从命令行执行脚本,则可以像以前一样执行此操作,如果您想从解释器中使用它:
import useArg
useArg.main(['foo', 'bar'])
In this case you have to use some dummy value at the first position of the list, so most of the time much better solution is to use argparse library . 在这种情况下,您必须在列表的第一个位置使用一些虚拟值,因此大多数时候更好的解决方案是使用argparse库 。 You can also check the number of command line arguments before calling the main function:
您还可以在调用main函数之前检查命令行参数的数量:
import sys
def main(arg):
print(arg)
if __name__ == '__main__':
if len(sys.argv) == 2:
main(sys.argv[1])
else:
main('Oops')
You can find good explanation what is going on when you execute if __name__ == '__main__':
here: What does if __name__ == "__main__": do? 你可以找到很好的解释当你执行
if __name__ == '__main__':
时会发生什么if __name__ == '__main__':
这里: if __name__ ==“__ main__”:怎么办?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.