Call Python script from bash with argument

前端 未结 8 809
长发绾君心
长发绾君心 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:08

    and take a look at the getopt module. It works quite good for me!

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

    To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance

    > python python_script.py var1 var2
    

    To access these variables within python you will need

    import sys
    print sys.argv[0] # prints python_script.py
    print sys.argv[1] # prints var1
    print sys.argv[2] # prints var2
    
    0 讨论(0)
  • 2020-11-29 17:14

    use in the script:

    echo $(python python_script.py arg1 arg2) > /dev/null
    

    or

    python python_script.py "string arg"  > /dev/null
    

    The script will be executed without output.

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

    I have a bash script that calls a small python routine to display a message window. As I need to use killall to stop the python script I can't use the above method as it would then mean running killall python which could take out other python programmes so I use

    pythonprog.py "$argument" & # The & returns control straight to the bash script so must be outside the backticks. The preview of this message is showing it without "`" either side of the command for some reason.

    As long as the python script will run from the cli by name rather than python pythonprog.py this works within the script. If you need more than one argument just use a space between each one within the quotes.

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

    Print all args without the filename:

    for i in range(1, len(sys.argv)):
    print(sys.argv[i])
    
    0 讨论(0)
  • 2020-11-29 17:23

    Use

    python python_script.py filename
    

    and in your Python script

    import sys
    print sys.argv[1]
    
    0 讨论(0)
提交回复
热议问题