Skip to content
Advertisement

How to create our own linux command for python code file

I am new to python. As a part of my project, I am trying to create a linux command for the python file which I have already. For example I have a python file example.py,

with open('file.txt','r') as f:
    for i in f:
        print i
with open('file.txt','r') as f:     #for different reasons I am opening file again
    for i in f:
        print i

Here I am trying to make a command like $example --print file.txt . Which means I am giving the input file from the command itself. Then it has to print the content of the input file. Please help me how to achieve this one. Thanks in advance.

Advertisement

Answer

You need to add the interpreter to the head of your script and also use the sys.env to access the input parameters:

#!/usr/bin/python

import sys, os;

# check so we have enough arguments
if len(sys.argv) < 2:
  printf "You need to supply at least two arguments."
  exit(-1)

# check so the file exists
if os.path.exists(sys.argv[1]):
  # try to open the filename supplied in the second argument
  # the sys.argv[0] always points to the name of the script
  with open(sys.argv[1], 'r') as f:
    for i in f:
      print i
else:
  print 'The file %s does not exists' %(sys.argv[1])

Notice that you might need to change the /usr/bin/python to the path where your python binary is installed. You can find out where it is by issuing the following command:

whereis python

Now you should be able to run your command like this:

./command file.txt

Notice, that here I assume that you are standing in the same folder as the python script. You could also move the script into a folder which is in your $PATH environment variable so you could access it from everywhere. For instance you could move it to /usr/local/bin:

mv command /usr/local/bin/.

You should then be able to run it from any folder using:

command file.txt

The last thing you need to do is to make sure the script is executable:

chmod +x command
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement