0

I am really struggling trying to figure out to pass variables from a bash script to a python function I have made. I have looked over numberous posts about the same issue and cant seem to understand what I am missing.

I have a python function script named fname_function.py:

from glob import glob
import os
import sys

first_arg=sys.argv[1]
second_arg=sys.argv[2]
third_arg=sys.argv[3]

def gFpath(reach,drive,date):
    list1 = glob(os.path.normpath(os.path.join(drive, reach, date,'*')))
    list2 =[]
    for afolder in list1:
      list2.append(glob(os.path.normpath(os.path.join(drive, reach, date, afolder, 'x_y_class?.asc'))))
    return list2

if __name__=='__main__':
    gFpath(first_arg,second_arg,third_arg)

And my bash script looks like:

reach="R4a"
drive= "D:\\"
dte="2015_04"

fnames=$(python fname_function.py "$reach" "$drive" "$dte")

for fname in $fnames; do echo "Script returned $fname"; done

The variables are being passed to the python script, but I cant seem to get list2 back to my shell script.

Thanks,

Dubbbdan

1 Answer 1

3

You can just run the Python file directly, like python fname_function.py "$reach" "$drive" "$dte"

However, sys.argv[0] will be fname_function.py in this case, so you'll want to set first_arg to sys.argv[1] and increment the other numbers as well.

Also, you don't output anything in your Python script. You should make the end of your script read:

if __name__=='__main__':
    fnames = gFpath(first_arg,second_arg,third_arg)
    for fname in fnames:
        print(fname)

which will print out 1 result from gFpath on each line.

Sign up to request clarification or add additional context in comments.

3 Comments

gFpath was designed to return a list of file paths to the bash script. How would I access list2 from the shell script?
You can assign the output to a variable in bash like so: fnames=$(python fname_function.py "$reach" "$drive" "$dte"). You can then loop over them with for fname in $fnames; do echo "Script returned $fname"; done. This might screw up if there are spaces in the filenames but I can't test on bash right now.
Thanks so much for you help! How ever when i implement the fname=... suggestion I am getting gfnames.sh: line 4: D:\: is a directory I was intentionally making it a directory i could change when I am working on different drives. Any ideas on how to pass a variable that resembles a directory?

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.