I want to implement my pypy.py script on commandline, I need to work with setup tools but the console_script does not work properly as my pypy.py needs two arguments, please guide me how can I modify it properly to work on commendline.
python.py
def main(agru1, argu2):
"do something"
if __name__ == "__main__":
main()
when I include it in my setup.py file, as console_script as follow
setup(
entry_points={
'console_scripts': ['pypy = pypy.pypy:main'],
}
)
And I get the following error when I run it on commandline:
Traceback (most recent call last):
File "/usr/local/bin/python", line 9, in <module>
load_entry_point('Pypy==0.1', 'console_scripts', 'pypy')()
TypeError: main() takes at least 2 arguments (0 given)
Entry points are a type of metadata that can be exposed by packages on installation. They are a very useful feature of the Python ecosystem, and come specially handy in two scenarios: 1. The package would like to provide commands to be run at the terminal. This functionality is known as console scripts.
The console_scripts Entry Point Setuptools allows modules to register entrypoints which other packages can hook into to provide certain functionality. It also provides a few itself, including the console_scripts entry point.
package_dir = {'': 'lib'} in your setup script. The keys to this dictionary are package names, and an empty package name stands for the root package. The values are directory names relative to your distribution root.
The entry point must be a function that may be invoked using exactly zero arguments. If you want to pass in arguments from the command line, say you want to invoke it like:
$ pypy a1 a2
You need to read them from sys.argv
instead. So your python module should contain this:
def program(arg1, arg2):
print(arg1, arg2)
def main():
import sys
arg1, arg2 = sys.argv[1], sys.argv[2]
program(arg1, arg2)
if __name__ == "__main__":
main()
Alternatively, the main
function may instead take an argv
argument that defaults to sys.argv
if importing sys
is desirable at the top level of the module:
def main(argv=sys.argv):
program(argv[1], argv[2])
Running that command as above should print out a1 a2
into the console. Error handling on user input is your own exercise.
Similar to the answer of metatoaster, instead of using sys.argv
you can use argsparse
https://docs.python.org/3/library/argparse.html, which makes the passing of argumnets a bit more user-friendly.
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--arg1', help='arg1 help')
parser.add_argument('--arg2', help='arg2 help')
args = parser.parse_args()
print("arg1 {}, arg2 {}".format(args.arg1, args.arg2)
Call it like:
pypy --arg1 1 --arg2 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With