Adding command line parameters to a python program

Adding command line parameters to a python program

·

1 min read

I wanted MeshTalk to have command line parameters for the following:

  • send message
  • receive messages
  • time to wait before exiting

To do this in Python is fairly straightforward. Import the module argparse and create an entry for each argument along with the data type, default value (if any) and some help information.

Example:

2021-09-09 16_04_57-● meshtalk.py - pi [SSH_ meshtasticPi.local] - Visual Studio Code.jpg

Code sample:

NAME = 'MeshTalk'                   
DESCRIPTION = "Send and recieve messages to a MeshTastic device"
DEBUG = False

parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('-s', '--send',    help="send a text message")
parser.add_argument('-r', '--receive', help="receive and display messages")
parser.add_argument('-t', '--time',    default = 60, help="seconds to listen before exiting")
args = parser.parse_args()


if(args.send):
  SendMessage = True

if(args.receive):
  ReceiveMessages = True

if(args.time):
  TimeToSleep = args.time

In my case I have three input arguments "-s" or "--send" for sending a message "-r" or "receive" for receiving messages "-t" or "time" for how many seconds to wait while listening to incoming messages

In my next post we will discuss how to use these parameters to control the logic.