Home  >  Article  >  Backend Development  >  Can shell execute python?

Can shell execute python?

anonymity
anonymityOriginal
2019-06-14 11:42:504432browse

Can shell execute python?

Can shell execute python?

Actual case: shell calls python script and passes parameters to python script

In shell:

python test.py $para1 $para2

In python:

import sys
def main($canshu1, $canshu2)
  .....
main(sys.argv[1], sys.argv[2])

Use shell to call functions in python:

The python script is as follows, test.py :

import ConfigParser  
  
config = ConfigParser.ConfigParser()  
config.read("test.conf")  
  
def get_foo():  
    return config.get("locations", "foo")  
  
def get_bar():  
    return config.get("locations", "bar")

I want to call get_foo inside through the shell. I only need to execute a calling command line in the shell:

python -c 'import test; print test.get_foo()'

The -c option just tells python to execute some python command.

To store the result in a variable, you can thus do:

RESULT_FOO=`python -c 'import test; print test.get_foo()'`

Or, equivalently:

RESULT=$(python -c 'import test; print test.get_foo()')

We can also call all methods at once, putting In a collection, call the cutting method to get the corresponding value:

ALL_RESULTS=$(python -c 'import test; print test.get_foo(), test.get_bar()')

If you need the second result, put it into RESULT_BAR:

 RESULT_BAR=$(echo $ALL_RESULTS | cut -d' ' -f2)

The above is the detailed content of Can shell execute python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn