Skip to content Skip to sidebar Skip to footer

How To Pass Parameter To Python Script From Unix

I have been researching over the internet like How to pass parameter to inside python code which is embedded within Unix function Overview : function_name() { python -c << E

Solution 1:

OP's approach will work, but casting to int while accessing environment variable is wrong since these are strings. However, there are many other types and issues:

  • OP is not exporting the environment variables, so they won't be accessible from the script.
  • The open call has a typo, the second argument should be 'r' instead of `r'.
  • The END of here document can't be indented.

Some of the above problems also exist with OP's first example that apparently worked, but I don't see anyway it could have.

Here is a function that works (note that the content inside here document is indented with a hard tab character). Also, OP is opening the file but not doing anything with the contents, so I added a loop showing its use (needed for my own test):

concatenate_ABC()
{
    read -r -d '' script <<-"----END"
    import os
    get_path=os.environ['a']
    get_filename=os.environ['b']
    get_nm=os.environ['c']
    
    with open(get_path+'/'+get_filename, 'r') as f:
        for line in f:
            fname=get_path +'/' +line.strip()+'/'+ get_nm 
            print(fname) 
----END
    export a="$1"export b="$2"export c="$3"
    python -c "$script"
}

Considering one can also pass arguments to python -c, we don't actually need to make use of environment variables (again watch for tab chars):

concatenate_ABC()
{
    read -r -d '' script <<-"----END"import sys
    get_path = sys.argv[1]
    get_filename = sys.argv[2]
    get_nm = sys.argv[3]
    
    withopen(get_path+'/'+get_filename, 'r') asf:
        for line inf:
            fname=get_path +'/' +line.strip()+'/'+ get_nm 
            print(fname) 
----END
    python -c "$script" $*
}

Post a Comment for "How To Pass Parameter To Python Script From Unix"