简体   繁体   English

如何使用if __name__ =='__main__'条件创建控制台脚本?

[英]How to create a console script using if __name__ == ' __main__' condition?

I am creating a setup file for python script installation. 我正在创建用于python脚本安装的安装文件。 Commonly, the documentation use for example the next setup file: 通常,文档使用例如下一个安装文件:

from setuptools import setup

# setup.py file
setup(name='test',
      version='0.0.0',
      packages=['test'],
      entry_points={
      'console_scripts': [
              'test = test.test:main'
           ]
         },
      )

to call this: 称之为:

# test/test.py file
def main():
    print('Hello!')

if __name__ == '__main__':
    main()

But, my problem is that I have my "main" code function below the if __ name__ == '__ main __' condition. 但是,我的问题是我的“主要”代码功能位于if __ name__ =='__ main __'条件之下。 I Can not create a main() function because this represents a big change an effort of development 我无法创建main()函数,因为这代表着开发工作的巨大变化

Are there any solution? 有什么解决办法吗? or I have to spend time creating a main() (or any name) function? 还是我必须花时间创建main()(或任何名称)函数?

As I understand it, you've got a bunch of code that you want to call only when the file isn't being imported (that's what that if statement does). 据我了解,只有在不导入文件的情况下,您才有一堆代码想要调用(这就是if语句所做的事情)。 However, it'd be very annoying, I'm sure, to add a tab before each line. 但是,我敢肯定,在每行之前添加一个选项卡会很烦人。

Solution: use something like this (works if you have linux; sure there are alternate solutions) , which is sed -i 's/^/\\t\\t/' <filename> on a separate file with your main code copy-pasted in to add tabs. 解决方案:使用类似的方法(如果您使用linux,则可以使用;请确保有其他解决方案) ,将sed -i 's/^/\\t\\t/' <filename>放在单独的文件中,并复制粘贴主代码在中添加标签。 Copy paste this tabbed code into your def main(): and voila. 复制此选项卡式代码粘贴到def main(): ,瞧。

However, it looks like this is just meant to be imported, and that's why you're using the setup.py file...in which case you don't need to do this, because presumably you want this code to run, and that's why you're importing it. 但是,看起来这只是要导入的,这就是您使用setup.py文件的原因……在这种情况下,您无需执行此操作,因为您可能希望运行此代码,并且这就是为什么要导入它。 (Unless it's some testing stuff.) (除非是一些测试内容。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM