我有一個test.py包含以下代碼的 python 腳本。
def f(x):
if x < 0:
raise Exception("negative number")
else:
return x
我撰寫了另一個test.sh在其中運行 python 函式的 shell 腳本。代碼如下
#!/bin/bash
X=$1
y=$(python3 -c "from test import f; print(f(`echo $X`))")
echo this is y: $y
當輸入為正時,shell 腳本作業正常,即bash test.sh 1. 這給了this is y: 1.
但是,當輸入為負時,即bash test.sh -1。它提供了一個 python 回溯。
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/user/test.py", line 4, in f
raise Exception("negative number")
Exception: negative number
this is y:
問題:應該進行哪些更改以避免上述輸出(避免列印回溯)。
預期輸出:
this is y: exception
uj5u.com熱心網友回復:
使用try/except列印的exception.
y=$(python3 -c "from test import f
try: print(f(`echo $X`))
except: print('exception')")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496505.html
