简体   繁体   English

Python 直接从命令行运行外部库 class

[英]Python run external lib class directly from command line

So imagine i have an external lib called printer with one file that looks like this.所以想象一下,我有一个名为打印机的外部库,其中包含一个看起来像这样的文件。

# in file ExternalLibPrinter.py
def main():
   print("hello external lib")
 

if __name__ == "__main__":
    main()

Now i've installed this via pip.现在我已经通过 pip 安装了这个。

What I would like to do is run that main function.我想做的是运行主要的 function。 If this was a python file that in my directory i would simply run如果这是在我的目录中的 python 文件,我只需运行

python3 ExternalLibPrinter.py

but I cant find such a file.但我找不到这样的文件。 I've also tried我也试过

python3 printer/ExternalLibPrinter.py

This can't find that file either.这也找不到那个文件。 So is this not possible?那么这不可能吗?

Use this code to call the main function:使用此代码调用主function:

import printer.ExternalLibPrinter as printer
printer.main()

If however the main() function was in the module's __init__.py , you would call it this way:但是,如果main() function 在模块的__init__.py中,您可以这样称呼它:

import printer
printer.main()

If you want to know where are the library's files stored, do this:如果您想知道库的文件存储在哪里,请执行以下操作:

$ python3
>>> import printer
>>> printer
<module 'printer' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/printer/__init__.py'>

In this example it shows where printer is installed on my computer, but that may be different with yours.在此示例中,它显示了printer在我的计算机上的安装位置,但可能与您的不同。

If the library is a single file, it will be called printer.py .如果库是单个文件,它将被称为printer.py If is is in multiple files, there will be a directory named printer which will contain: __init__.py — File that is used when you write import printer and for each submodule there will be a file submodulename.py that is used when you write import printer.submodulename .如果是在多个文件中,将有一个名为printer的目录,其中将包含: __init__.py — 编写import printer时使用的文件,并且对于每个子模块,将有一个文件submodulename.py在编写import printer.submodulename时使用import printer.submodulename

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

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