Skip to main content

Command Palette

Search for a command to run...

Adding command line parameters to a python program

Updated
1 min read
Adding command line parameters to a python program
D

I started programming when I was 11. Microsoft Basic on a TRS-80 computer.

Moved on to learn Pacal, C, C++, Cobol, SQL, PHP, Powershell, Python.

Been coding for 40 years and loving it.

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.

More from this blog

T

This Old Coder

15 posts

I am a life long programmer. I work with SQL Server professionally, and I code Python on Raspberry Pi computers for fun. I am also a professional photographer, an arcade and pinball enthusiast.