Shell捕获Python返回值,而不是打印值。

huangapple go评论65阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月1日 15:52:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76379760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定