Home > Back-end >  How to run Python file using a unique commandb instead of using 'python' keyword
How to run Python file using a unique commandb instead of using 'python' keyword

Time:06-01

This may sound silly, but I just need to know how this is possible.

I have a python file 'hello.py' which accepts an arguement using argParse.

The code is as below:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--message", type=str, required=True)
args = parser.parse_args()

message = args.message
print(f'Your message: {message}' )

The code works as expected when I run: python hello.py --message "Hi my name is Tony"
And I get the following as the output:

Your message: Hi my name is Tony

However, the requirement is that when I the command, I want to run it in such a way that python hello.py can be substituted to a unique command.

Example: hello --message "Hi my name is Tony"

Want it in such a way that I could run this command hello from any directory. Kind of need it like an environment variable. Does anyone know how to achieve this setup?

CodePudding user response:

Check out this post: https://gist.github.com/umangahuja1/51da3a453803f1f67f4eee5de129d4db

Essentially what you want to do is modify your script to tell the system it should use python path to run rather than shell. After that you turn permissions to make it executable and then run it.

CodePudding user response:

You can use sys to get the args

import sys

and then get the args like that:

args = sys.args()

when you run it, use:

py hello.py argument1 argument2
  • Related