2014-10-01 68 views
-2

我正在制作一个脚本,用于读取跟踪代码,查看将跟踪发布到网站的结果并打印一些消息并具有返回值。 这里是Python代码的一部分:如何在shell脚本中读取输出和外部程序的返回值?

# update return True if there was a change to the .msg file 
def update(cod): 
    msg = extract_msg(cod) 
    if msg == 'ERROR': 
     print('ERROR: invalid code\n') 
     sys.exit(2) 
    file = open('.msg', "r+") 
    old_msg = file.read() 
    if msg == old_msg: 
     return False 
    else: 
     print('Previous message: ' + old_msg) 
     print('Latest message: ' + msg) 
     file = overwrite(file, msg) 
     file.close() 
     return True 

def main(argv): 
    if len(argv) > 1: 
     cod_rastr = argv[1] 
    else: 
    print("Error: no arg, no code\n") 
    return -1 
    # Verify if file exists 
    if os.path.isfile(".msg") == False: 
     arq = open('.msg', 'w') 
     arq.close() 
    # post() returns the source code of the resulting page of the posted code. 
    cod = post(cod_rastr) 
    if update(cod) == False: 
     return 0 
    else: 
     print ('\n Message!\n') 
     return 1 

在这里,我想不仅是阅读印刷品(最后用户),但返回的值(有条件使用)。这个脚本应该阅读的.py的输出,并把我的情况下,有从上次检查更新的邮件(我把这个脚本在crontab):

#!/bin/bash 
if [ -z "$1" ]; then 
    echo usage: $0 CODE 
    exit 
fi 

CODE=$1 
STATUS=$(myscript.py $CODE 2>&1) 
VAL=$? 
FILE=$(<.msg) 
# always prints 0 (zero) 
echo $VAL 
# I want to check for an existing update case 
if [[ $STATUS == 'Message!' ]] 
then 
    echo $STATUS 
    echo $FILE | mail [email protected] -s '$CODE: Tracking status' 
fi 

的问题是,$?总是返回0,我的字符串检查里面的if,没有工作,因为我认为它读取update()也会打印,它在打印中有变量。 如何在不更改python脚本的情况下运行此shell脚本?

在此先感谢。

+0

...是整个python脚本?你似乎没有运行'main'。脚本是否独立工作?看看'sys.exit()'...... – bryn 2014-10-02 00:16:44

+0

不是,正如我所提到的那样,它只是它的一部分,与相关的代码。我运行main并且脚本需要'requests'模块。 查看'sys.exit()'是什么意思? – user3404142 2014-10-10 00:12:07

回答

0

我怀疑你可以做你想要的子进程模块。使用rc = subprocess.call(...)获取返回码,同时将stdout指向文件,或使用p = subprocess.Popen(...),然后使用p.communicate获取输出,并使用p.returncode获取返回码。