Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Setuptools: quick way to add scripts without "main" function as "console_scripts" entry points

My request seems unorthodox, but I would like to quickly package an old repository, consisting mostly of python executable scripts.

The problem is that those scripts were not designed as modules, so some of them execute code directly at the module top-level, and some other have the if __name__=='__main__' part.

How would you distribute those scripts using setuptools, without too much rewrite?

  • I know I could just put them under the scripts option of setup(), but it's not advised, and also it doesn't allow me to rename them.
  • I would like to skip defining a main() function in all those scripts, also because some scripts call weird recursive functions with side effects on global variables, so I'm a bit afraid of breaking stuff.
  • When I try providing only the module name as console_scripts (e.g "myscript=mypkg.myscript" instead of "myscript=mypkg.myscript:main"), it logically complains after installation that a module is not callable.

Is there a way to create scripts from modules? At least when they have a if __name__=='__main__'?

like image 925
PlasmaBinturong Avatar asked May 30 '26 13:05

PlasmaBinturong


1 Answers

I just realised part of the answer:

in the case where the module executes everything at the top-level, i.e. on import, it's therefore ok to define a dummy "no-op" main function, like so:

# Content of mypkg/myscript.py

print("myscript being executed!")

def main():
    pass  # Do nothing!

This solution will still force me to add this line to the existing scripts, but I think it's a quick but cautious solution.

No solution if the code is under a if __name__=='__main__' though...

like image 96
PlasmaBinturong Avatar answered Jun 02 '26 01:06

PlasmaBinturong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!