【发布时间】:2014-10-01 19:43:47
【问题描述】:
我正在编写一个脚本来读取跟踪代码,查看将跟踪发布到网站的结果并打印一些消息并具有返回值。 这是python代码的一部分:
# 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 myuser@mydomain.com -s '$CODE: Tracking status'
fi
问题是$? 总是返回0,并且我在 if 中的字符串检查不起作用,因为我认为它也读取了 update() 打印,它在打印中有变量。
如何在不更改 python 脚本的情况下让这个 shell 脚本运行?
提前致谢。
【问题讨论】:
-
...这是整个 python 脚本吗?你似乎没有在运行
main。脚本可以独立运行吗?查看sys.exit()... -
不是,正如我提到的,它只是其中的一部分,带有相关代码。我确实运行 main 并且脚本需要
requests模块。查看sys.exit()是什么意思?
标签: shell python-3.x return-value stdout stderr