You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python脚本sys.exit无输出问题:如何输出0或1退出码?

解决Python脚本退出码无输出的问题

Hey there! I get why this might be confusing—let's clear it up.

Your code is actually working correctly in terms of setting the exit code, but here's the thing: sys.exit(n) sends that exit code to the operating system, not directly to your terminal as visible output. That's why you don't see 0 or 1 printed when you run the script.

Here are two ways to get the result you want:

1. Print the exit code before exiting (if you want it visible in the terminal)

Modify your script to explicitly print the number before calling sys.exit():

import sys
List = ['a', 'b', 'c', 'd']
if 'c' in List:
    print(0)
    sys.exit(0)
else:
    print(1)
    sys.exit(1)

Now when you run the script, you'll see 0 or 1 printed right away.

2. Check the exit code from your terminal (if you don't need the script to print it)

If you just need to verify the exit code after running the script, you can access it through your shell:

  • On Linux/macOS (bash/zsh): Run your script, then type echo $? and hit enter. This will show the exit code of the last command (your script).
  • On Windows Command Prompt: Run the script, then type echo %errorlevel% to see the exit code.

A quick note:

Exit codes are meant for the OS and other programs to understand if your script succeeded (0) or failed (non-zero). They aren't designed to be visible to users by default—so either printing them manually or checking via the shell is the way to go.

内容的提问来源于stack exchange,提问作者Kiran

火山引擎 最新活动