0

I have a python script, let's call it my_script.py. The script is supposed to generate simulated responses to an api call performed on the command line.

What I am looking for is some way to have a custom command line command, e.g. run-my-script execute my_script.py while allowing for my_script.py to accept keyword arguments.

It would be great to have a solution that doesn't require external libraries and that allows for keyword arguments to be passed from the command line to that function.

Is there a way to have a custom command on the command line, like run-my-script trigger my_script.py?

Though it would be easiest to just run python my_script.py from the command line, for my use case I need to have the python script triggered just by run-my-script alone.

lespaul
  • 477
  • 2
  • 8
  • 21
  • 2
    You can rename your script to `run-my-script` if you already have the shebang line, then copy it to somewhere on your path. – Selcuk Jan 07 '20 at 00:12
  • 2
    Like a shell script named `run-my-script` that itself runs `python3 my_script.py "$@"`? – jarmod Jan 07 '20 at 00:18
  • @jarmod That is probably one solution. But it seems like more work than necessary since you can run `my_script.py` directly without a shell script wrapper. – Code-Apprentice Jan 07 '20 at 00:48
  • @Code-Apprentice agreed, if the only thing the shell script does is exec the Python script. I figured it might be more complex than that, but maybe it isn’t. – jarmod Jan 07 '20 at 00:51

2 Answers2

2

alias run-my-script="python my_script.py"

Run this command in terminal and run-my-script will execute my_script.py.

You can also add it in ~/.bashrc so you can access it after you reboot.

aligumustosun
  • 152
  • 10
1

You should first add a shebang line to your Python script:

#!/usr/bin/env python3

Then you can run it directly from the command line as

$ my_script.py

If you want the command to be something else, then just rename your file. If you want to run it from any directory, copy it to a directory that is already in you PATH or add it's parent directory to your PATH.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268