如何编写一个用python调用的bash脚本? [英] How to write a bash script which calls itself with python?

查看:47
本文介绍了如何编写一个用python调用的bash脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下这个bash脚本如何工作吗?我不了解的部分是":" ,这种语法在bash中意味着什么?

Can someone explain how this bash script works? The part I don't understand is """:", what does this syntax mean in bash?

#!/bin/sh 

""":"

echo called by bash
exec python $0 ${1+"$@"}

"""

import sys
print 'called by python, args:',sys.argv[1:]

测试运行结果:

$ ./callself.sh xx
called by bash
called by python, args: ['xx']


$ ./callself.sh
called by bash
called by python, args: []

推荐答案

那很聪明!在Bash中":将仅扩展为:,这是空命令(不执行任何操作).因此,接下来的几行将被执行,从而导致 exec .此时,Bash 停止存在,并且该文件被Python重新读取(名称为 $ 0 ),并且转发了原始参数.

That's clever! In Bash, the """:" will be expanded into only :, which is the empty command (it doesn't do anything). So, the next few lines will be executed, leading to exec. At that point, Bash ceases to exist, and the file is re-read by Python (its name is $0), and the original arguments are forwarded.

$ {1 +"$ @"} 的意思是:如果定义了 $ 1 ,则将参数"$ @" 作为参数传递是原始的Bash脚本参数.如果未定义 $ 1 ,表示Bash没有参数,则结果为空,因此不传递任何其他内容,甚至不传递空字符串.

The ${1+"$@"} means: If $1 is defined, pass as arguments "$@", which are the original Bash script arguments. If $1 is not defined, meaning Bash had no arguments, the result is empty, so nothing else is passed, not even the empty string.

在Python 中,""开始一个多行字符串,其中包括Bash命令,并一直扩展到结束的"" .因此,Python会跳到下面.

In Python, the """ starts a multi-line string, which includes the Bash commands, and extends up to the closing """. So Python will jump right below.

这篇关于如何编写一个用python调用的bash脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆