Home > front end >  Command line input in python using os and system
Command line input in python using os and system

Time:10-18

I am trying to run the iris_dataset using os.system from python, then while taking the values I am copying the value from iris_dataset to Temp and then I am opening the Temp file and using it like below.

import os

import sys

os.system("/home/mine/Desktop/C4.5/c4.5 -u -f iris_dataset")

os.system("/home/mine/Desktop/C4.5/c4.5rules -u -f iris_dataset > Temp")

f=open('Temp')

Once I am done with my program I am executing my program like : python3 prog_name.py In this case whenever I am using any other dataset apart from iris_dataset, I need to open the program again and change that name in the above code where iris_dataset is written.

Instead of this I just want to make a change i.e while executing the program I want to write : python3 prog_name.py my_data_set_name in kind of command line, so that it becomes more easy to change the datasets as per my wish.

CodePudding user response:

Use sys.argv

import os

import sys

dataset = sys.argv[1]

os.system(f"/home/mine/Desktop/C4.5/c4.5 -u -f {dataset}")

os.system(f"/home/mine/Desktop/C4.5/c4.5rules -u -f {dataset} > Temp")

f=open('Temp')

Please note that I used python's f-strings for better code readability. Feel free to use the dataset variable in any way you see fit

sys.argv documentation

CodePudding user response:

You could use click to create a nice console line interface. It can give you nice help text, options etc.

For example:

import os
import click

@click.command()
@click.argument("dataset")
def init(dataset):
    """
    DATASET - Dataset to process
    """
    process_dataset(dataset)


def process_dataset(dataset):
    os.system(f"/home/mine/Desktop/C4.5/c4.5 -u -f {dataset}")
    os.system(f"/home/mine/Desktop/C4.5/c4.5rules -u -f {dataset} > Temp")
    f=open('Temp')
    ...

if __name__ == "__main__":
    init()
  • Related