Similar command to python’s Try for shellscript?

Asked

Viewed 46 times

-1

I need to formulate a . sh to run a code if the first error:

!#/bin/bash

python main.py
python3 main.py

As if it were a python (Try/Except) exception.

I thought about creating two . sh scripts, to use Try in a python file, where it would decide which script runs without errors, but I don’t know if it’s feasible. If so, a good idea, how to have python run these files. sh?

  • similar question to this one: https://answall.com/questions/427389/loop-para-rodar-scripts-python/427390#427390

1 answer

2


Just use two pipes || (OR)

!#/bin/bash

python main.py || python3 main.py

If the syntax fails in Python 2 (I believe your goal) then it will execute the python3

resultado no Debian

In the example the script was:

import sys

version = sys.version

# Python 3
# value = f"Version: {version}"

# Python 2 e 3
value = "Version: " + version

print(version)

See that he printed Version 2.7.16

Now if you change the comments of the lines to:

import sys

version = sys.version

# Python 3
value = f"Version: {version}"

# Python 2 e 3
# value = "Version: " + version

print(version)

The result will be Version 3.7.3 (in my case, your machine may have different versions of Python 2 and 3)

resultado python3 no debian

You may have noticed that you still have the error when you tried to run a Python2 syntax in Python3, before trying Python3, if you want to "delete" this type of message in the terminal you can use the 2>/dev/null in Python 2:

!#/bin/bash

python main.py 2>/dev/null || python3 main.py

In Python3 do not need, after all if fail in both the error is something else.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.