You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# show Python version
python --version
# start an interactive Python shell
python
# run a Python script
python script.py
# run a module as a script
python -m module_name
# run one line of Python
python -c "print('hello')"
Virtual Environments and Packages
# create a virtual environment
python -m venv .venv
# activate a virtual environment on macOS or Linuxsource .venv/bin/activate
# deactivate the active virtual environment
deactivate
# upgrade pip
python -m pip install --upgrade pip
# install packages
python -m pip install pandas numpy
# save installed packages
python -m pip freeze > requirements.txt
# install packages from a requirements file
python -m pip install -r requirements.txt
Basic Script Pattern
# define the script entrypointdefmain():
print("hello")
# run main only when this file is executed directlyif__name__=="__main__":
main()
Imports and Paths
# import a standard library modulefrompathlibimportPath# build a path safelydata_path=Path("data") /"input.csv"# check whether a file existsifdata_path.exists():
print(data_path)
# list files matching a patternforpathinPath("data").glob("*.csv"):
print(path)
File I/O
# read a whole text filewithopen("input.txt", "r") asfile:
text=file.read()
# write text to a filewithopen("output.txt", "w") asfile:
file.write("hello\n")
# read a CSV file with pandasimportpandasaspddf=pd.read_csv("data.csv")
# write a CSV file with pandasdf.to_csv("output.csv", index=False)
Lists and Dictionaries
# create a listvalues= [1, 2, 3]
# add an item to a listvalues.append(4)
# loop over a listforvalueinvalues:
print(value)
# create a dictionarysample= {"name": "A", "count": 10}
# get a dictionary valuecount=sample["count"]
Functions and Errors
# define a functiondefadd_one(value):
returnvalue+1# call a functionresult=add_one(10)
# raise an error when input is invalidifresult<0:
raiseValueError("result must be nonnegative")
Command Line Arguments
# parse command line argumentsimportargparseparser=argparse.ArgumentParser()
parser.add_argument("--input", required=True)
args=parser.parse_args()
print(args.input)
Debugging
# run a script with the Python debugger
python -m pdb script.py
# run tests with pytest
python -m pytest
# stop execution at a breakpointbreakpoint()
# print a quick debug valueprint(f"value={value!r}")