Passing python array to bash script (and passing bash variable to python function)

后端 未结 5 777
感情败类
感情败类 2021-01-02 16:27

I have written a Python module which contains functions that return arrays. I want to be able to access the string arrays returned from the python module, and iterate over i

5条回答
  •  孤独总比滥情好
    2021-01-02 16:57

    As well as Maria's method to obtain output from python, you can use the argparse library to input variables to python scripts from bash; there are tutorials and further docs here for python 3 and here for python 2.

    An example python script command_line.py:

    import argparse
    import numpy as np
    
    if __name__ == "__main__":
    
        parser = argparse.ArgumentParser()
    
        parser.add_argument('x', type=int)
    
        parser.add_argument('array')
    
        args = parser.parse_args()
    
        print(type(args.x))
        print(type(args.array))
        print(2 * args.x)
    
        str_array = args.array.split(',')
        print(args.x * np.array(str_array, dtype=int))
    

    Then, from a terminal:

    $ python3 command_line.py 2 0,1,2,3,4
    
    # Output
    
    
    4
    [0 2 4 6 8]
    

提交回复
热议问题