关于Python中if __name__ == '__main__':的问题
您好,请教一个很初级的python问题:
我在研究BitTorrent的时候自己写了一段代码,存入testMain.py这个文件:
#!/usr/bin/env python
# -*- coding: cp936 -*-
# Written by Bram Cohen
# see LICENSE.txt for license information
import sys
sys.path.append('D:\develop\Python\BitTorrent-3.3\BitTorrent')
sys.path.append('D:\develop\Python\BitTorrent-3.3')
from sys import argv
from BitTorrent.parseargs import parseargs, formatDefinitions
defaults = [
('piece_size_pow2', 18,
"which power of 2 to set the piece size to"),
('comment', '',
"optional human-readable comment to put in .torrent"),
('target', '',
"optional target file for the torrent")
]
if __name__ == '__main__':
if len(argv) < 3:
print 'usage is -'
print argv[0] + ' file trackerurl [params]'
print
print formatDefinitions(defaults, 80)
else:
try:
config, args = parseargs(argv[3:], defaults, 0, 0)
print 'config',config
print 'args',args
except ValueError, e:
print 'error: ' + str(e)
print 'run with no args for parameter explanations'
我觉得我的问题应该很初级,但是我确实没看到相关资料,只在Python编程宝典时看到了这样一段描述的话:
从if __name__ == '__main__':往下的代码是通用于许多GUI程序的一项约定。该行检测名称空间是否为
“__main__”,并在条件成立(即为文件调用了解释器)的前提执行后续语句。如果文件作为一个模块导入,
该条件就不成立,如果程序单独运行,而非作为模块在另一个程序中使用,后续语句就会执行。
我现在的问题是,如何才能使程序单独运行,或者如何才能使程序在shell下单独运行,并且输入我的程序参数。
我作了以下尝试:
>>> import testMain
>>> dir()
['__builtins__', '__doc__', '__name__', 'argv', 'defaults', 'formatDefinitions', 'parseargs', 'sys', 'testMain']
>>> testMain
<module 'testMain' from 'D:\PROGRA~1\Python\testMain.py'>
>>> testMain arg01 arg02
SyntaxError: invalid syntax
>>> testMain
<module 'testMain' from 'D:\PROGRA~1\Python\testMain.py'>
>>> testMain [arg01,arg02]
Traceback (most recent call last):
File "<pyshell#15>", line 1, in -toplevel-
testMain [arg01,arg02]
NameError: name 'arg01' is not defined
>>> testMain ['','']
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-
testMain ['','']
TypeError: unsubscriptable object
>>> testMain [myfile, http://myfile/announce]
SyntaxError: invalid syntax
>>> testMain ['myfile.txt', 'http://myfile/announce']
Traceback (most recent call last):
File "<pyshell#18>", line 1, in -toplevel-
testMain ['myfile.txt', 'http://myfile/announce']
TypeError: unsubscriptable object
>>>
都没能找到在命令行调用该模块的方式
请指教