简体   繁体   English

如何从没有安装 pip 的模块执行 python function

[英]how to execute python function from module without pip install

How can I execute python function from a package without main / pip install in editable mode如何在没有主 / Z62AD1C2A46C5298F3E2C95D3 的 package 的情况下执行 python function

eg例如

my sample.py is我的 sample.py 是

def cli():
    print("I'm running myTest")
    return 0

and setup.py as和 setup.py 作为

setup(
    name="sample",
    version="1.0",
    py_modules=["sample"],
    include_package_data=True,
    entry_points="""
        [console_scripts]
        sample=sample:cli
    """,
)

now if I do pip install -e.现在如果我做pip install -e. and execute sample I get desired o/p as并执行我得到想要的 o/p 的sample

I'm running myTest

However with this I'm not able to debug it, What's ideal way to execute function from a module without pip install / using another python file,但是,我无法调试它,从没有 pip 安装/使用另一个 python 文件的模块执行 function 的理想方法是什么,

also tried with python -m sample but that gives no o/p since there is no entrypoint还尝试使用python -m sample ,但由于没有entrypoint点,因此没有给出 o/p

So call your function in your sample.py :所以在你的sample.py中调用你的 function :

def cli():
    print("I'm running myTest")
    return 0

if __name__ == "__main__":
    cli()

Then, from the command line:然后,从命令行:

python sample.py

See here for what if __name__ == "__main__": means: https://www.freecodecamp.org/news/if-name-main-python-example/请参阅此处了解if __name__ == "__main__":表示: https://www.freecodecamp.org/news/if-name-main-python-example/

If you want to leave sample.py completely unmodified, then you just create a new file test_sample.py and import sample to use it like so:如果您想完全不修改sample.py ,那么您只需创建一个新文件test_sample.pyimport sample以像这样使用它:

import sample

sample.cli()

or, as an alternative method of import, test_sample.py can also be:或者,作为导入的替代方法, test_sample.py也可以是:

from sample import cli

cli()

Then you run:然后你运行:

python test_sample.py

Just make sure test_sample.py is in the same directory as sample.py .只需确保test_sample.pysample.py位于同一目录中。

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

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