raoulbia raoulbia - 10 days ago 6
Bash Question

Pass argument from shell script to Python script without having to specify argument on command line

I want to execute a shell script without having to specify any additional arguments on the command line itself. Instead I would like to hard code the arguments, e.g. input file name and file path, in the shell script.

Toy shell script:

#!/bin/bash

time python3 path/to/pyscript/graph.py \
--input-file-path=path/to/file/myfile.tsv


So, when I run
$ ./script.sh
, the script should pass the input file information to the py script.

Can this be done? I invariably get the error "no such directory or file" ...

Note, I will deal with the arguments on the python script side using
argparse
.

EDIT

It turns out that the issue was caused by something I had omitted from my toy script above because I didn't think that it could be the cause. In fact I had a line commented out and it was this line which prevented the script from running.

Toy shell script Full Version:

#!/bin/bash

time python3 path/to/pyscript/graph.py \
# this commented out line prevents the script from running
--input-file-path=path/to/file/myfile.tsv

jDo jDo
Answer

I suspect your script is correct but the file path is wrong. Maybe you forgot a leading forward slash. Anyway, make sure that path/to/pyscript/graph.py and path/to/file/myfile.tsv are correct.

A dummy example of how to call a python script with hard-coded arguments from a BASH script:

$ cat dummy_script.py 
import argparse
import os
import time

parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input-file-path")
args = parser.parse_args()

if os.path.isfile(args.input_file_path):
    print args.input_file_path, "is a file"
    print "sleeping a second"
    time.sleep(1)

$ cat time_python_script.sh
time python dummy_script.py --input-file-path=/etc/passwd

$ /bin/bash time_python_script.sh
/etc/passwd is a file
sleeping a second

real    0m1.047s
user    0m0.028s
sys 0m0.016s