简体   繁体   English

如何将控制权从python脚本返回给调用bash脚本?

[英]How can I return control from my python script to the calling bash script?

I am using a bash script to loop through a configuration file and, based on that, call a python script via ssh. 我正在使用bash脚本循环遍历配置文件,并基于此通过ssh调用python脚本。 Unfortunately once the Python script does its job and I call quit the bash script also gets closed, therefore the calling bash script's loop is terminated prematurely. 不幸的是,一旦Python脚本完成了工作并且我quit了,bash脚本也会被关闭,因此调用bash脚本的循环会提前终止。

Here's my Bash Script 这是我的Bash脚本

target |  grep 'srv:'  | while read l ; do srv $l $SSH ; done

 srv () {
 SSH=$2
 SRV=`echo $1 | awk -F: '{print $2}'`
 STATUS=`echo $1 | awk -F: '{print $3}'`
 open $SSH "srv" $SRV $STATUS
 }

then on the remote machine where the python script is called 然后在远程机器上调用python脚本

if __name__== "main":
   redirect('./Server.log', 'false')
   conn()
   if sys.argv[1] == "srv":
     ServerState(sys.argv[2], sys.argv[3])
   quit()

So looks like the quit() is also interrupting the script. 因此,看起来quit()也在中断脚本。

Nothing that the remote Python script does should be able to kill your do loop unless you have done a set -e in the local bash first to make it sensitive to command failure — in which case it would die only if, as @EOL says, your remote script is hitting an exception and returning a nonzero/error value to SSH which will then die with a nonzero/error code locally. 除非您先在本地bash中执行set -e使其对命令失败敏感,否则远程Python脚本确实不会杀死do循环,在这种情况下,只有@EOL说,您的远程脚本遇到异常,并向SSH返回一个非零/错误值,它将在本地死于非零/错误代码。

What happens if you replace do srv with do echo srv so that you just get a printout of the commands you think you are running? 如果将do srv替换为do echo srv以便仅获得您认为正在运行的命令的打印输出,会发生什么情况? Do you see several srv command lines get printed out, and do they have the arguments you expect? 您是否看到几个srv命令行被打印出来,并且它们具有您期望的参数?

Oh: and, why are you using open to allocate a new Linux virtual terminal for every single run of the command? 哦:而且,为什么要使用open为命令的每次运行分配一个新的Linux虚拟终端? You do not run out of virtual terminals that way? 您不会用完虚拟终端吗?

It looks like quit() is the function that makes your program stop. 看起来quit()是使程序停止的函数。

If you can remove the call to quit() (ie if it does nothing), just remove it. 如果您可以删除对quit()的调用(即,如果它什么也不做),则将其删除。

Otherwise, you can run your Python program by hand (not from a shell script) and see what happens: it is likely that your Python script generates an exception, which makes the shell script stop. 否则,您可以手动运行Python程序(而不是从Shell脚本运行)并查看会发生什么:您的Python脚本很可能会生成异常,这会使Shell脚本停止。 By running your Python program manually with realistic arguments (on the remote machine), you should be able to spot the problem. 通过在实际参数上(在远程计算机上)手动运行Python程序,您应该能够发现问题。

您应该能够简单地从main函数返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM