Python编程-python与其它语言的互相调用(二):如何在python代码中调用shell脚本

本节内容:

在上一节演示了shell中调用python脚本,本节介绍python调用shell。
 

代码:hello_main.py:

用python调用shell, 再在shell中调用python的例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#用python调用shell, 再在shell中调用python的例子
import os
import sys

cmd_shell='call_by_sh.sh'

def do_shell(cmd):
	print('=========start do_shell========')
	print(cmd)
	status=os.system(cmd)
	print(status)
	if status == 0:
		print('success end')
	else:
		print('fail end')

#main
if __name__ == '__main__':
	print('=========start hello_main.py========')
	input_len = len(sys.argv)
	print('input params len:')
	print(input_len)

	if input_len >=1:
		print('input params:')
		cmd=cmd_shell
		for i in range(input_len):
			print(sys.argv[i])
			if i>0:
				cmd=cmd + ' ';
				cmd=cmd+sys.argv[i]
		do_shell(cmd)
	else:
		raise("input params error!!!")


	

	

代码说明:

os.system(cmd)执行shell命令,参数cmd就是shell命令。

cmd_shell='call_by_sh.sh':是shell脚本,具体代码参考上一节:

https://blog.csdn.net/liranke/article/details/113967299

Python编程-python与其它语言的互相调用(一):如何在shell中调用python代码

 

for i in range(input_len): for循环用于将接收到的参数(例如,从命令行接收)传递给shell脚本,作为shell脚本的输入参数。

 

运行结果:

aaaaa:note_py user1$ python3 hello_main.py aa
=========start hello_main.py========
input params len:
2
input params:
hello_main.py
aa
=========start do_shell========
call_by_sh.sh aa
main begin...
当前目录/Users/user1/work/zy/stu_py/chaper/note_py
程序名称./call_by_sh.sh
程序参数aa
init...
init参数aa
call hello.py:
input param:
aa
main end.
0
success end

其中,main begin...  ~  main end.  就是shell中的输出,当然,这当中还包括了shell再调用python的输出。


如果觉得有用,点赞,评论,转发 :)

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liranke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值