[Python] 【python】Python与shell的交互

338 0
Honkers 2026-4-2 00:26:49 | 显示全部楼层 |阅读模式

一,shell调用python

1,shell直接调用python

shell调用python是比较简单的,直接在.sh脚本中输入执行命令即可,跟在linux环境下没有什么两样:

加上“python”是具有软连接的;

  1. python filename.py
复制代码

2,shell传参到python的函数并得到返回数据

使用sys来接收参数。使用python -c来调用python的函数。

python端接收为:

  1. import sys
  2. def function1():
  3. #print('参数个数为:', len(sys.argv), '个参数。')
  4. #print('参数列表:', str(sys.argv))
  5. inputarg=sys.argv[1]
  6. return inputarg+"Back"
复制代码

shell端调用python函数为:

  1. arg="FromShell"
  2. RESULT_FOO=`python3 -c 'import table_monitor_util;print(table_monitor_util.function1())' $arg`
  3. echo "RESULT_FOO is:"$RESULT_FOO
复制代码

这样就可以在shell端,把形参直接传到python的函数中,并得到该函数处理完的结果数据。

输出为:

  1. RESULT_FOO is:FromShellBack
复制代码

二,Python调用shell

Python根据版本的不同需要使用不同的Python库,Python2的话是使用"commands"的库,执行起来非常简单:

  1. exe2_sql = 'ls -l'
  2. # 分别接收执行后的状态以及返回结果
  3. (status, output) = commands.getstatusoutput(exe2_sql)
复制代码

Python3没有commands,据说可以用subprocess库代替,暂时还没用过。

最简单的可以用os.popen,如下所示:

  1. import os
  2. temp = os.popen("ls")
  3. for line in temp.readlines():
  4. line=line.strip()
  5. print(line)
复制代码

subprocess库的用法:python3- subprocess模块. 学习记录_superwshu-CSDN博客_python3 subprocess

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行