如何运行python程序包_运行一个python包

Running Python 2.6.1 on OSX, will deploy to CentOS. Would like to have a package to be invoked from a command line like this:

python [-m] tst

For that, here is the directory structure made:

$PYTHONPATH/

tst/

__init__.py # empty

__main__.py # below

dep.py # below

The following is in the files:

$ cat tst/__main__.py

from .dep import DepClass

print "Hello there"

$ cat tst/dep.py

class DepClass(object):

pass

$

However, python gives me conflicting diagnostic:

$ python -m tst

/usr/bin/python: tst is a package and cannot be directly executed

OK, so it is recognized as a package. So I should be able to run it as a script? It has __main__...

$ python tst

Traceback (most recent call last):

File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/runpy.py", line 121, in _run_module_as_main

"__main__", fname, loader, pkg_name)

File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/runpy.py", line 34, in _run_code

exec code in run_globals

File "/Users/vdidenko/Code/emi/tst/__main__.py", line 1, in

from .dep import DepClass

ValueError: Attempted relative import in non-package

At this point I am lost. Why non-package? And how to structure the code then?

解决方案

The feature to run the __main__ module of a package when using the command line -m option was introduced in Python 2.7. For 2.6 you need to specify the package module name to run; -m test.__main__ should work. See the documentation here.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值