1

I want to create terminal commands in my python script.

for example,

$ cd my_project_folder
$ --help (I use a command in this python folder)

outputs
$ this is the help command. You've activated it using --help. This is only possible because you cd'd to the folder and inputted this command.

I am looking for user defined commands ( ones that I've already defined in my python function.)

I am not looking for commands like 'ls' and 'pwd'.

Nqx
  • 17
  • 5
  • Does this answer your question? [How to execute a program or call a system command from Python?](https://stackoverflow.com/questions/89228/how-to-execute-a-program-or-call-a-system-command-from-python) – IoaTzimas Jan 12 '21 at 22:09
  • no. I want to make my own commands. Let's say I've already printed 'my name is joe'. Now if the user enters '--hello', a command I made, the script will print 'hi!' – Nqx Jan 12 '21 at 22:10
  • @Nqx so what I understood, you are looking for calling a script just by `$ some_defined_command` ? For example `$ hello` and it calls a python function? – Leemosh Jan 12 '21 at 22:50
  • @Leemosh Correct! – Nqx Jan 13 '21 at 02:30

3 Answers3

2

You can use os.system, as below:

import os
os.system('your command')
IoaTzimas
  • 8,393
  • 2
  • 9
  • 26
  • I haven't defined anything there though. Is this for commands like 'ls' and 'cd' ? also, I apologize if I havent' clarified anything in my initial question. – Nqx Jan 12 '21 at 22:12
1

Use os module if you wanna execute command that is specific to bash or shell that you use

import os
os.system("string command")

As Leemosh sugested you can use click module to make your own commands that are related to scripts

And you can also use sys module to read args that you put affter your script example

$ python3 name_of_script.py arg_n

import sys
if sys.argv[1] == "commnd":
    do something
  • I want the commands to be done in terminal itself, or while the script is in running. Is this possible? Should I just repeatedly use input commands? – Nqx Jan 13 '21 at 02:47
1

What you are looking for is creating a setup.py file and defining some entry points. I'd recommend watching https://www.youtube.com/watch?v=GIF3LaRqgXo&ab_channel=CodingTech or https://www.youtube.com/watch?v=4fzAMdLKC5ks&ab_channel=NextDayVideo to better understand how to deal with setup.py.

from setuptools import setup

setup(
    name="Name_of_your_app",
    version="0.0.1",
    desciption="some description",
    py_modules=["app"], # I think you don't need that
    package_dir={"": "src"}, # and probably you don't need this as well
    entry_points={"console_scripts": {"THIS_IS_THE_DEFINED_COMMAND=app:main"}},
)

app is name of the py file, main is function you wanna call.

app.py

def main():
    print("hello")
Leemosh
  • 551
  • 3
  • 9