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的输出。


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

猜你喜欢

转载自blog.csdn.net/liranke/article/details/114022244
今日推荐