【问题标题】:How to make a python script execute another command if one does not?如果没有,如何让 python 脚本执行另一个命令?
【发布时间】:2021-02-01 03:43:06
【问题描述】:

示例:假设我编写了这样的代码:(只是一个示例)

#开始

url = 'www.example.com'
response = request.urlopen(url)
result = request.read().decode('utf-8')
print(result) #End

但是,假设我想实现一些使脚本在代码中执行修改的东西,例如:utf-8 无法解码,如果发生这种情况,代码将更改或执行一些其他代码,而无需发送它.decode(utf-8)

那就是:

response = request.urlopen(url)
result = response.read().decode('utf-8')
print(result)

无法使用utf-8 解码 然后代码更改...或某些command 执行它下面的代码,然后代码重新执行:

result = response.read()
print (result) **#END**

【问题讨论】:

  • google 异常处理/Try 语句

标签: python python-3.x python-requests command


【解决方案1】:

这是一个示例实现,其中 2 个命令中有 1 个不起作用。

def iDontWork():
    # This is a random example, where division by zero will not work.
    return 1/0

def iDoWork():
    # This is a random working method.
    return 1/1

try:
    iDontWork()
except Exception:
    iDoWork()
    print("First function (iDontWork) didn't work, so function the second function (iDoWork) started working.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多