如何在同一个文件中编写脚本/库?

时间:2017-03-24 12:12:32

标签: python

我想使用python实现某些功能,可以通过两种方式使用:

  1. 简单的命令行脚本,如python mylib.py
  2. 通过导入其他python代码
  3. 我的第一次尝试看起来像这样。

    mylib.py:

    from __future__ import print_function
    import sys
    
    class A(object):
        def __init__(self, args):
            print("my args: {}".format(args))
    
    def main():
        a = A(sys.argv)
        print("got {}".format(a))
    
    main()
    

    我可以直接调用或使用其他地方,例如usage.py:

    import mylib
    
    mylib.A("bla")
    

    这样可行,但似乎导入导致main()也被执行:

    python scripts/using.py blub
    my args: ['scripts/using.py', 'blub']
    got <mylib.A object at 0x7ff17bc736d0>
    my args: bla
    

    问题:

    • 当我选择main()时,有没有办法阻止python using.pl投放?

    除此之外:

    • 这是一个好方法吗?或者我在这里违反了python中已经建立的最佳实践?
    • 换句话说:我有什么不该做的事情吗?

2 个答案:

答案 0 :(得分:2)

这就是你添加

的原因
def patchify(img, patch_shape):
    img = np.ascontiguousarray(img)  # won't make a copy if not needed
    X, Y = img.shape
    x, y = patch_shape
    shape = ((X-x+1), (Y-y+1), x, y) # number of patches, patch_shape
    # The right strides can be thought by:
    # 1) Thinking of `img` as a chunk of memory in C order
    # 2) Asking how many items through that chunk of memory are needed when indices
    #    i,j,k,l are incremented by one
    strides = img.itemsize*np.array([Y, 1, Y, 1])
    return np.lib.stride_tricks.as_strided(img, shape=shape, strides=strides)

如果直接调用此.py文件,您的if __name__ == '__main__': main() 将会运行。如果您的文件只是导入,则不会运行mainSee here

答案 1 :(得分:0)

由于@CoryKramer已经回答了问题的第一部分,让我来看看第二部分。

代码应该存在于它所属的位置。如果它与解析脚本或主执行有关,那么它应该在脚本中。任何其他代码都不应该是脚本文件的一部分。

通常,在生产代码中,您永远不应从脚本文件导入。公共代码应该存在于它自己的类中的单独文件中,或者只是在程序方法的情况下存在于单独的文件中。这样,脚本中的代码就会非常简洁,并且公共文件中的代码可以在其他生产代码中重复使用,并且您不会冒着意外执行脚本的风险,只需使用公共代码。

# common.py
class A(object):
    def __init__(self, args):
         print("my args: {}".format(args))

# mylib.py
from common import A

if __name__ == '__main__':
    a = A(sys.argv)
    print("got {}".format(a))