ShanZhengYang ShanZhengYang - 1 month ago 9
Python Question

How to distribute code to be executed by an external command? Bash script?

EDIT: Based on discussions below, I think my question really could apply to any language. Python naturally has a packaging system and installation procedure via

pip
. But let's say this was C code or a perl script. Users would still download the program files, and have a way to execute the code in the command line via
capsall input.txt
.

I have a python script that takes an input file and gives an output file.

For a concrete example, this script
file1.py
takes in an input text file and outputs a text file with all letters capitalized:

import sys
inFile = sys.argv[1]
outFile = sys.argv[2]

with open(inFile,'r') as input_file:
lines = input_file.readlines()

# process the input file somehow
# here we simply capitalize the text,
# but naturally something more complex is possible

capitalized_lines = []
for line in lines:
capitalized_lines.append(line.upper())

with open(outFile,'w') as output_file:
for line in capitalized_lines:
output_file.write(line)


The way users execute this code now with

python file1.py input.txt output.txt


Let's say I wanted to distribute this code such that users would download a tarball and be able to execute the above in the command line with (for example)

capsall input.txt


which would run
python file1.py
and output the file
output.txt
. Does one write a bash script? If so, how do you distribute the code such that users will have this in their PATH?

Answer

Add a "hash bang" at the top of the script file to tell bash to invoke the Python interpreter. Also make your script executable:

#!/usr/bin/env python
import sys

inFile = sys.argv[1]
outFile = sys.argv[2]
...

Make the script file executable:

$ cp file1.py capsall
$ chmod +x capsall

Now you can run the script with:

$ ./capsall input.txt output.txt

Or if capsall is on your path:

$ capsall input.txt output.txt