Call Python script from bash with argument

前端 未结 8 810
长发绾君心
长发绾君心 2020-11-29 16:37

I know that I can run a python script from my bash script using the following:

python python_script.py

But what about if I wanted to pass a

相关标签:
8条回答
  • 2020-11-29 17:27

    Embedded option:

    Wrap python code in a bash function.

    #!/bin/bash
    
    function current_datetime {
    python - <<END
    import datetime
    print datetime.datetime.now()
    END
    }
    
    # Call it
    current_datetime
    
    # Call it and capture the output
    DT=$(current_datetime)
    echo Current date and time: $DT
    

    Use environment variables, to pass data into to your embedded python script.

    #!/bin/bash
    
    function line {
    PYTHON_ARG="$1" python - <<END
    import os
    line_len = int(os.environ['PYTHON_ARG'])
    print '-' * line_len
    END
    }
    
    # Do it one way
    line 80
    
    # Do it another way
    echo $(line 80)
    

    http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html

    0 讨论(0)
  • 2020-11-29 17:31

    Beside sys.argv, also take a look at the argparse module, which helps define options and arguments for scripts.

    The argparse module makes it easy to write user-friendly command-line interfaces.

    0 讨论(0)
提交回复
热议问题