3

I have a python code like so

wallpaper/
   setup.py
   wallpaper/
      __init__.py
      environments.py
      run.py

The run.py has a function like so:

import environments

def main():
   .. do something()
if __name__=='__main__':
   main()

After installing this package how do I execute the run.py script on my terminal. I realize this question has been asked before but I wasn't satisfied with that answer as it did not offer me any insight.

Atia
  • 100
  • 1
  • 3
  • 15
  • `python run.py` if you want to execute exactly run.py or `python -m wallpaper` if `wallpaper` is a module and it available for python interpreter. – Yarick Oct 08 '17 at 17:26
  • It depends on how you "install" your package. Please provide more details. – randomir Oct 08 '17 at 18:15

2 Answers2

4

You want

python -m wallpaper.run

This relies on PYTHONPATH being set properly; you may need to restart your terminal if the package was just installed in a new directory.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
1

To run the main function in your run.py file from the command line, you'll need to set the entry_points option in your setup.py file. This can be done by adding the following code:

setup(
    OTHER_SETTINGS,
    entry_points={"console_scripts": ["yourcmd= wallpaper.run:main"]},
)

This code creates an executable script called yourcmd that runs the main function from the wallpaper.run module when it's invoked from the command line. To run this script, simply open a new terminal and enter yourcmd.

If you're not familiar with entry_points(refer to this answer and this documentation), it's a way to define commands that can be run from the command line after installing your package. By specifying entry_points with "console_scripts" as the key, you can create executable scripts that run a function within your package. This is useful if you want to make your package easily accessible from the command line without users having to manually navigate to the package directory and run the file themselves.

For a real-world example, you can check out the setup.py file for the open source project fast-entry_points.

Lerner Zhang
  • 6,184
  • 2
  • 49
  • 66