最近,在Mac Os下,写一下自动化脚本,经常需要用shell调用python,或者反过来,用python调用shell。

本节内容介绍的是如何用shell调用python。

例子如下:

使用shell调用python的函数。

call_by_sh.sh:

#!/bin/bash

main()
{
    echo 'main begin...'
    cur_dir=`pwd`
    pythonPATH=""
    
    cmd=$0
    filePath=$1

    #echo $filePath

    echo 当前目录$cur_dir
    echo 程序名称$cmd
    echo 程序参数$filePath

    init $filePath
    echo 'main end.'
    return
}

init(){
    echo 'init...'
    packDir=$1
    echo init参数$packDir
    echo 'call hello.py:'
    hello.py $1

}

#$1 输入path name
main $*

hello.py:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import sys

def print_hello(data_str):
	print(data_str)

#main
if __name__ == '__main__':
	print_hello('input param:')
	print_hello(sys.argv[1]) #argv1需要从外部传入

 

运行结果:

aaaaa:note_py user1$ ./call_by_sh.sh aaa
main begin…
当前目录/Users/user1/work/stu_py/chaper/note_py

程序名称./call_by_sh.sh
程序参数aaa
init…
init参数aaa
call hello.py:
input param:
aaa
main end.

代码简单说明:

#!/bin/bash,表示用的是bash shell解释器;

main() 和init()都是函数,就像其他语言一样;

hello.py $1: 调用hello.py脚本,将执行hello.py的main;

main $*,  这条语句是shell执行的第一个语句;

 

 

 

 

本文地址:https://blog.csdn.net/liranke/article/details/113967299