[英]Python function returns different values when executed from a Bash script
I have a sample Python file "Test_exit.py":我有一个示例 Python 文件“Test_exit.py”:
import os
def test_exit():
print('Line 1.\n')
print('Line 2.\n')
exit (17)
if __name__ == '__main__':
test_exit()
When I execute it using Python, it works as expected:当我使用 Python 执行它时,它按预期工作:
ubuntu@ip-172-31-9-235:~$ python3 Test_exit.py
Line 1.
Line 2.
When I check the returned error code, it does print "17" as expected:当我检查返回的错误代码时,它会按预期打印“17”:
ubuntu@ip-172-31-9-235:~$ echo $?
17
However, things work different when I execute the same Python file from a Bash script "Test_exit.sh":但是,当我从 Bash 脚本“Test_exit.sh”执行相同的 Python 文件时,情况会有所不同:
#!/bin/bash
Exit_code=$(python3 Test_exit.py)
echo $Exit_code
I would expect it to echo "17", but it doesn't:我希望它会回显“17”,但它不会:
ubuntu@ip-172-31-9-235:~$ ./Test_exit.sh
Line 1. Line 2.
Not only it doesn't echo "17", but now the two lines are printed without a new line...不仅没有回显“17”,而且现在这两行都打印出来了,没有换行……
If I replace exit (17)
with sys.exit (17)
, then nothing is printed, not even the 2 lines in a single line...如果我将exit (17)
替换为sys.exit (17)
,则不会打印任何内容,甚至不会打印单行中的 2 行...
What's wrong with my code?我的代码有什么问题? Does exit
cause not only Python to exist, but Bash script as well? exit
是否不仅导致 Python 存在,而且 Bash 脚本也存在? And why are strings printed differently depending on how Python is called?为什么字符串的打印取决于 Python 的调用方式?
EDIT编辑
For future reference, here is the script that works well, as advised by @choroba:为了将来参考,这里是运行良好的脚本,由@choroba 建议:
#!/bin/bash
output=$(python3 Test_exit.py)
Exit_code=$?
echo "$Exit_code"
echo "$output"
The command substitution $(...)
doesn't return the exit code, it captures the output.命令替换$(...)
不返回退出代码,它捕获 output。 Use $?
使用$?
to check the exit code.检查退出代码。
output=$(python3 Test_exit.py)
exit_code=$?
To get the exact output, you need to double quote the variable:要获得准确的 output,您需要将变量双引号:
echo "$Exit_code"
Without quotes, the variable is expanded and undergoes word-splitting, so each word in the output is treated as a separate argument to echo
which leads to reduction of whitespace to single spaces.如果没有引号,变量会被扩展并进行分词,因此 output 中的每个单词都被视为echo
的单独参数,从而导致空格减少为单个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.