M
Modular16mo ago
Egod

cmd args parse

I want to use the argparse package in Python, but it's painful to write a mojo code like
from python import (Python, PythonObject)

fn main():
try:
let ap = Python.import_module("argparse")
let parser = ap.ArgumentParser()
parser.add_argument(...) # this line is painful since key args are not supported yet
...
except e:
print(e.value)
from python import (Python, PythonObject)

fn main():
try:
let ap = Python.import_module("argparse")
let parser = ap.ArgumentParser()
parser.add_argument(...) # this line is painful since key args are not supported yet
...
except e:
print(e.value)
thus I think it will be more reasonable to implement a simple argparse in mojo.... The question is that is there any existing codes? or would Modular offer official module in the future?
9 Replies
ziyu4huang
ziyu4huang16mo ago
I will do whole things in Python to handle args in python only. Simply. in main.mojo fn main(): let args_dict = Python.import_module("my_app").parse() ... do things in mojo. in my_pp.py: def parse(): parser = argparse.ArgumentParser(): parser.add_argument(...) # do the easy things in Python. Really, there is no benefit to write simple glue code in Mojo. It wil be painful and useless .
rd4com
rd4com16mo ago
yes, good use!
Jack Clayton
Jack Clayton16mo ago
Mojo has this: https://docs.modular.com/mojo/stdlib/sys/arg.html Keyword arguments are being worked on currently
bhavnicksm
bhavnicksm16mo ago
Hey @Jack Clayton, could you give an example on how to use this function argv? Mojo is throwing a errors when I am trying it in a pythonic fashion
Jack Clayton
Jack Clayton16mo ago
Hi @bhavnicksm sure:
from sys import argv

fn main():
print(argv()[1])
from sys import argv

fn main():
print(argv()[1])
Then you can pass in the argument:
mojo run argvtest.mojo arg1
mojo run argvtest.mojo arg1
But it does result in a crash if you don't pass in the arg, I've raised an issue here for that: https://github.com/modularml/mojo/issues/827
bhavnicksm
bhavnicksm16mo ago
Thanks @Jack Clayton!
arboverda
arboverda11mo ago
would have to check length of argv() before accessing argv()[1], right? I mean, to avoid the crash, you've mentioned actually - now it no longer crashes but prints "(null)"
Jack Clayton
Jack Clayton11mo ago
Yeah should do that
Want results from more Discord servers?
Add your server