7

I'm using Python 2.7, and I have the following simple script, which expects one command line argument:

#!/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 ?

4

1 回答 1

6

你不能。将代码包装在函数中

#!/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)

如果你从命令行执行你的脚本,你可以像以前一样,如果你想从解释器中使用它:

import useArg
useArg.main(['foo', 'bar'])

在这种情况下,您必须在列表的第一个位置使用一些虚拟值,因此大多数情况下更好的解决方案是使用argparse library。您还可以在调用 main 函数之前检查命令行参数的数量:

import sys

def main(arg):
    print(arg)

if __name__ == '__main__':
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        main('Oops') 

你可以在这里找到很好的解释当你执行时发生了什么if __name__ == '__main__':if __name__ == "__main__": do?

于 2013-09-17T15:09:33.133 回答