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'.

4
  • Does this answer your question? How to execute a program or call a system command from Python? Commented Jan 12, 2021 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!' Commented Jan 12, 2021 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? Commented Jan 12, 2021 at 22:50
  • @Leemosh Correct! Commented Jan 13, 2021 at 2:30

3 Answers 3

2

You can use os.system, as below:

import os
os.system('your command')
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

1 Comment

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?
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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.