【问题标题】:Grab return value from python with Shell Script使用 Shell 脚本从 python 中获取返回值
【发布时间】:2016-11-29 12:23:11
【问题描述】:

我知道已经提出并回答了类似的问题。
但是,我的问题涉及的问题类型和实施略有不同:

情况是:
我需要构建一个 shell 脚本,它将捕获 python (2.7) 脚本的返回值,然后将其用于 jenkins 作业。
在 python 脚本中,我必须读取一个 SVN 签出文本文件并返回文件的值,更新文件的值,然后提交。

我已经实现了以下代码:

swdl_number_receiver.py

import posixpath
import os
import sys
import subprocess

SVN_VERSION_DIR_PATH = 'data'
SWDL_FILE_NAME = "swdl_number.txt"

# Exit codes
class ExitCode:
   """ Exit code Enumeration """
    SUCCESS = 0
    FAILURE = 1

# get SWDL number from the file
def getSWDLNumber():
work_dir = posixpath.join(os.getcwd(),SVN_VERSION_DIR_PATH)
version_number = None
new_version_number = None

# Read the File
os.chdir(work_dir)
with open(SWDL_FILE_NAME, "r") as input_file:
    for line in input_file:
        version_number = str.strip(line)
        if version_number is None:
            print "---- SWDL NUmber is empty existing the code ....... "
            sys.exit(ExitCode.FAILURE)
        else:
            print "++++ The found SWDL number is : " + version_number
            new_version_number = int(version_number) + 1
            print "++++ The New SWDL Number is  : " + str(new_version_number)

print "++++ Writing the new SWDL Number from " + str(version_number) + " to " + str(new_version_number)
#replace the file with new content
os.remove(SWDL_FILE_NAME)
with open(SWDL_FILE_NAME, 'wb') as output:
    output.write(str(new_version_number).rstrip('\n'))

checkin_message = '"Updated SWDL Number to : ' + str(new_version_number) + '"'
try:
    subprocess.call(['svn', 'commit', '-m ' + checkin_message, SWDL_FILE_NAME, '--non-interactive'])
except:
    sys.exit(ExitCode.FAILURE)

return new_version_number


if __name__ == "__main__":
    print getSWDLNumber()

在我正在做的 shell 脚本中:

outputString=$(python swdl_number_receiver.py)
echo $outputString

swdl_number.txt 只包含一行 5 位数字。

我的问题: 当我注释掉所有“打印”行和 SVN 提交的 try and catch 时,我只得到 new_version_number 作为返回值。
换句话说,如果我取消注释所有带有打印语句的行以及 SVN 提交的 try 和 catch 块,那么在 shell 脚本中作为 $output_string 我得到每个打印语句和提交消息以及“new_version_number” .如果我注释掉所有打印语句并尝试捕获块,那么我会得到所需的“new_version_number”。

应如何修改我的代码以获得唯一需要的“new_version_number”返回并显示所有打印行?

【问题讨论】:

    标签: python bash python-2.7 shell


    【解决方案1】:

    outputString=$(python swdl_number_receiver.py)
    

    构造捕获发送到stdout 的文本。如果您希望您的脚本将信息打印到终端,那么您可以将其发送到stderr。这是一个简单的演示。

    qtest.py

    import sys
    
    print >>sys.stderr, "this is sent to stderr"
    print "this is sent to stdout"
    

    在 Bash 中:

    $ outputString=$(python qtest.py);echo "ok";echo "$outputString"
    

    输出

    this is sent to stderr
    ok
    this is sent to stdout
    


    以下是适用于 Python 2 和 Python 3 的 qtest.py 版本:
    from __future__ import print_function
    import sys
    
    print("this is sent to stderr", file=sys.stderr)
    print("this is sent to stdout")
    

    如果您还想在变量中捕获发送到stderr 的输出,一种方法是在不更改“qtest.py”的情况下将 Bash 中的stderr 重定向到文件:

    $ outputString=$(python qtest.py 2>qtemp);echo "ok";stderrString=$(<qtemp);echo "STDOUT: $outputString";echo "STDERR: $stderrString"
    ok
    STDOUT: this is sent to stdout
    STDERR: this is sent to stderr
    

    更好的方法是直接在 Python 中写入文件:

    qtest.py

    from __future__ import print_function
    
    with open("qtemp", "w") as f:
        print("this is sent to qtemp", file=f)
        print("this is sent to stdout")
    

    重击

    $ outputString=$(python qtest.py);echo "ok";qtempString=$(<qtemp);echo "STDOUT: $outputString";echo "qtemp: $qtempString"
    ok
    STDOUT: this is sent to stdout
    qtemp: this is sent to qtemp
    

    【讨论】:

    • 是的,您的实现正是我所寻找的,但是如何在变量中捕获这个sys.stderr。因为我需要将它放在一个变量中,以便以后可以使用该值。
    • @Nepal12 我在回答中添加了更多信息,希望对您有所帮助。
    【解决方案2】:

    好吧,您可以在 python 和 bash 之间共享您的version file。根据您的 python 脚本的退出代码,您可以决定您是否获得了有效的新版本。

    Shell 脚本:

    # Version file name
    SWDL_FILE_NAME="x.txt"
    export SWDL_FILE_NAME
    python swdl_number_receiver.py
    # Exit code of python script
    EXIT_CODE=$?
    
    if [ $EXIT_CODE -eq 0 ] ; then
            # If scripts exits successfully get version
            NEW_VERSION=$(cat $SWDL_FILE_NAME)
            echo "New version is $NEW_VERSION"
            exit 0
    else
            # No new version
            echo "Failed to get new version"
            exit 1
    fi
    

    最小的 Python 文件:

    import sys
    import os
    SWDL_FILE_NAME=os.environ['SWDL_FILE_NAME']
    with open(SWDL_FILE_NAME, 'w') as fp:
        fp.write("111")
    sys.exit(0)
    

    输出:

    $ ./myscript.sh 
    New version is 111
    

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2017-07-18
      • 2013-07-16
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多