Python Forum
calling external function with arguments
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
calling external function with arguments
#4
(Jun-24-2023, 01:11 PM)snippsat Wrote:
(Jun-23-2023, 04:43 AM)Wimpy_Wellington Wrote: If I call it from another python program the arguments are not found, I cannot figure out how to pass the arguments. How to do?
I may think there is confusion about using command line tool sys.argv, getopt(do not use as mention).
Because you don't use command line here at all,but try to call it from a other module using a string. tiny fishing

argparse Gribouillis show is ok,but can show a example with Typer which is really cool.
Here i also do rename on files on disk,not just show there names.
from pathlib import Path
import typer

app = typer.Typer()

@app.command()
def renameit(
    old_name: str = typer.Option(..., '-o', '--old-name'),
    new_name: str = typer.Option(..., '-n', '--new-name'),
):
    old_path = Path(old_name)
    if old_path.is_file():
        old_path.rename(Path(new_name))
        typer.echo(f'File renamed from {old_name} to {new_name}')
    else:
        typer.echo('File not found.')

if __name__ == '__main__':
    app() 
Using it,see that help and colors get(use Rich under the hood) get generated automatic.
[Image: ATaLiF.png]
Also using this in a other module only need to pass app,and it will work.
from rename_files import app

if __name__ == '__main__':
    app()
Thanks, it works.
Reply


Messages In This Thread
RE: calling external function with arguments - by Liliana - Jul-04-2023, 02:28 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 1,008 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Calling a function (which accesses a library) from another file mouse9095 4 864 Jun-07-2023, 08:55 PM
Last Post: deanhystad
Sad Iterate randint() multiple times when calling a function Jake123 2 2,127 Feb-15-2022, 10:56 PM
Last Post: deanhystad
  Calling a class from a function jc4d 5 1,908 Dec-17-2021, 09:04 PM
Last Post: ndc85430
  'namespace' shorthand for function arguments? shadowphile 5 2,670 Aug-11-2021, 09:02 PM
Last Post: shadowphile
  Checking the number of arguments a function takes Chirumer 3 2,244 Jul-06-2021, 04:56 PM
Last Post: Chirumer
  [Solved] TypeError when calling function Laplace12 2 2,960 Jun-16-2021, 02:46 PM
Last Post: Laplace12
  Possible to dynamically pass arguments to a function? grimm1111 2 2,251 Feb-21-2021, 05:57 AM
Last Post: deanhystad
  calling a function and argument in an input phillup7 3 2,679 Oct-25-2020, 02:12 PM
Last Post: jefsummers
  How to pass multiple arguments into function Mekala 4 2,504 Jul-11-2020, 07:03 AM
Last Post: Mekala

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020