Skip to content

Instantly share code, notes, and snippets.

@huynhbaoan
Last active January 5, 2024 07:47
Show Gist options
  • Save huynhbaoan/de4546d6b735519f624f76bf4dc18d5b to your computer and use it in GitHub Desktop.
Save huynhbaoan/de4546d6b735519f624f76bf4dc18d5b to your computer and use it in GitHub Desktop.
Python notes
### Handling error example
import sys
import traceback
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0]) #print type of exception
traceback.print_exc() #print the whole traceback stack
# raise ## raise exception to higher stack if necessary
finally:
# command will always run, regardless of the exception.
### refer: https://docs.python.org/3.7/tutorial/errors.html
### Run function inside a python file directly
def myfunction():
...
if __name__ == '__main__':
globals()[sys.argv[1]]()
python myscript.py myfunction
This works because you are passing the command line argument (a string of the function's name) into locals, a dictionary with a current local symbol table. The parantheses at the end will make the function be called.
update: if you would like the function to accept a parameter from the command line, you can pass in sys.argv[2] like this:
def myfunction(mystring):
print mystring
if __name__ == '__main__':
globals()[sys.argv[1]](sys.argv[2])
This way, running python myscript.py myfunction "hello" will output hello.
### Refer: https://stackoverflow.com/questions/3987041/run-function-from-the-command-line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment