英文:
Shell capture python return value, not print value
问题
我有一个Python脚本,既打印出一些值,又返回一些值。像这样:
(伪代码)
def 主函数:
打印 "你好"
返回 1
我希望Shell脚本能够捕获返回的值(1),而不是打印的值(你好)。
英文:
I have a python script that both prints and returns some value. Like:
(pseudo code)
def main:
print "hello"
return 1
I'd like the shell script to capture the value returned (1) not the value printed (hello).
答案1
得分: 3
从main()
函数返回一个值在这里不起作用。
要向操作系统(从而是一个shell脚本)返回一个退出代码,你应该使用sys.exit()
。
英文:
Returning a value from that main()
function doesn't do anything here.
To return an exit code to the operating system (and thus a shell script), you should use sys.exit()
.
答案2
得分: 1
The script needs to use sys.exit() in order to return a value to the caller. The returned value is limited to integers that can be expressed in 8 bits.
For example, we have foo.py implemented as:
import sys
print('All the world\'s a stage, And all the men and women merely players')
sys.exit(99)
Then, in another .py file, we can have:
from subprocess import run
print(run(['python3', 'foo.py'], capture_output=True).returncode)
Output:
99
英文:
The script need to utilise sys.exit() in order to pass back some value to the caller. The value that can be return is limited to integers that can be expressed in 8 bits
For example we have foo.py implemented as:
import sys
print('All the world\'s a stage, And all the men and women merely players')
sys.exit(99)
Then, in another .py file we can have:
from subprocess import run
print(run(['python3', 'foo.py'], capture_output=True).returncode)
Output:
99
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论