Can shell execute python?

anonymity
Release: 2019-06-14 11:42:50
Original
4418 people have browsed it

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
Copy after login

In python:

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

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")
Copy after login

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()'
Copy after login

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()'`
Copy after login

Or, equivalently:

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

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()')
Copy after login

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

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!