To read environment variables from a Python script or a Jupyter notebook, you would use this code—assuming you have a
.env file in the directory where your script or notebook lives.
# .env FOO=BAR S3_BUCKET=YOURS3BUCKET S3_SECRET_KEY=YOURSECRETKEYGOESHERE
# script.py import os print(os.environ.get('FOO')) # Empty
But this won't return the value of the environment variables, though, as you need to parse the contents of your
.env file first.
For that, you can either use
pip install python-dotenv
Then use this Python library to load your variables.
# Example from https://pypi.org/project/python-dotenv/ from dotenv import load_dotenv load_dotenv() # OR, the same with increased verbosity load_dotenv(verbose=True) # OR, explicitly providing path to '.env' from pathlib import Path # Python 3.6+ only env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) # Print variable FOO print(os.environ.get('FOO')) # Returns 'BAR'
Or load the variables manually with this script.
import os env_vars = !cat ../script/.env for var in env_vars: key, value = var.split('=') os.environ[key] = value # Print variable FOO print(os.environ.get('FOO')) # Returns 'BAR'
I got this error while trying to
pip3 install tensorflow. I tried
python3 -m pip install tensorflow as well — it didn't work.
ERROR: Could not find a version that satisfies the requirement tensorflow ERROR: No matching distribution found for tensorflow
As was my case, the reason for this error might be that you are using
pip from a Python version not yet supported by any version of TensorFlow. I was running Python 3.9 and TensorFlow only had compatibility up to Python 3.8. By creating a new environment with Python 3.8 (or reverting the current environment to use 3.8) I could
pip3 install tensorflow successfully.
About six months ago, Microsoft launched Pylance, a "fast and feature-rich language support for Python," available in the Visual Studio Code marketplace.
Pylance depends on our core Python extension and builds upon that experience, for those of you who have already installed it.
Among its main features are type information, auto-imports, multi-root workspace support, and type checking diagnostics.
The name Pylance serves as a nod to Monty Python’s Lancelot, who is the first knight to answer the bridgekeeper’s questions in the Holy Grail.
To write (or save) text to a file using Python, you can either append text or overwrite all existing contents with new text.
To append text, open the file in
append mode, write to it to add lines of text, and close it.
file = open('/path/to/file.txt', 'a') # 'a' is append-to-end-of-file mode file.write('Adding text to this document.') file.close()
You can also write the entire contents of the files, overwriting any existing content using the
w mode instead of
file = open('/path/to/file.txt', 'w') # 'w' is overwrite mode file.write('This will override any existing content in the text to this document.') file.close()
You can use
\n and other codes to add line breaks to your document.
file = open('/path/to/file.txt', 'w') # 'w' is overwrite mode file.write('First line.\nSecond line.\nThird line.\n\nNono.MA') file.close()
# file.txt First line. Second line. Third line. Nono.MA
To determine whether a file or directory exists using Python you can use either the
os.path or the
os library offers three methods:
import os # Returns True if file or dir exists os.path.exists('/path/to/file/or/dir') # Returns True if exists and is a file os.path.isfile('/path/to/file/or/dir') # Returns True if exists and is a directory os.path.isdir()
pathlib library has many methods (not covered here) but the
pathlib.Path('/path/to/file').exists() also does the job.
import pathlib file = pathlib.Path('/path/to/file') # Returns True if file or dir exists file.exists()
When manipulating semantic segmentation datasets, I found myself having to downsize segmentation masks without adding extra colors. If the image is cleanly encoded as a PNG, only the colors representing each of the classes contained in the label map will be present, and no antialias intermediate colors will exist in the image.
When resizing, though, antialias might add artifacts to your images to soften the edges, adding new colors that don't belong to any class in the label map. We can overcome this problem loading (or decoding) input images with TensorFlow as PNG and resizing our images with TensorFlow's
NEAREST_NEIGHBOR resizing method.
import tensorflow as tf # Read image file img = tf.io.read_file('/path/to/input/image.png') # Decode as PNG img = tf.io.decode_png( img, channels=3, dtype=tf.uint8 ) # Resize using nearest neighbor to avoid adding new colors # For that purpose, antialias is ignored with this resize method img = tf.image.resize( img, (128, 128), # (width, height) antialias=False, # Ignored when using NEAREST_NEIGHBOR method=tf.image.ResizeMethod.NEAREST_NEIGHBOR ) # Save the resize image back to PNG tf.keras.preprocessing.image.save_img( '/path/to/output/image.png', img )
Linters analyze code to catch errors and suggest best practices (using the abstract syntax tree, or AST). (Function complexity, syntax improvements, etc.)
Formatters fix style. (Spacing, line jumps, comments, etc.)
macOS ships with Python 2 by default, you can install set Python 3 as the default Python version on your Mac.
First, you install Python 3 with Homebrew.
brew update && brew install python
To make this new version your default, you can add the following line to your
~/.zshrc file (or
~/.bashrc if you want to expose it in
bash instead of
Then open a new Terminal and Python 3 should be running.
Let's verify this is true.
python --version # e.g. Python 3.8.5
Homebrew provides info about any installed "bottle" via the
brew info python # firstname.lastname@example.org: stable 3.8.5 (bottled) # Interpreted, interactive, object-oriented programming language # https://www.python.org/ # /usr/local/Cellaremail@example.com/3.8.5 (4,372 files, 67.7MB) * # ...
And you can find the path we're looking for
brew info python | grep bin # /usr/local/bin/python3 # /firstname.lastname@example.org/libexec/bin
You can also symlink
ln -sf /usr/local/bin/python3 /usr/local/bin/python
In case your
/usr/local/bin/python3 is also symlinked, you can check where it's symlinked to with:
In my case, it returns
Your system's Python 2.7 is still there.
/usr/bin/python --version # e.g Python 2.7.16
You can also use Homebrew's Python 2.
brew install python@2
I managed to make this work by unlinking
Then reinstalling python.
brew reinstall python@2
I was having this issue when trying to install Google Cloud SDK. After doing the previous steps, I could run the installer without a problem.
import polyscope as ps # Initialize polyscope ps.init() ### Register a point cloud # `my_points` is a Nx3 numpy array ps.register_point_cloud("my points", my_points) ### Register a mesh # `verts` is a Nx3 numpy array of vertex positions # `faces` is a Fx3 array of indices, or a nested list ps.register_surface_mesh("my mesh", verts, faces, smooth_shade=True) # Add a scalar function and a vector function defined on the mesh # vertex_scalar is a length V numpy array of values # face_vectors is an Fx3 array of vectors per face ps.get_surface_mesh("my mesh").add_scalar_quantity("my_scalar", vertex_scalar, defined_on='vertices', cmap='blues') ps.get_surface_mesh("my mesh").add_vector_quantity("my_vector", face_vectors, defined_on='faces', color=(0.2, 0.5, 0.5)) # View the point cloud and mesh we just registered in the 3D UI ps.show()
import connexion from connexion.resolver import RestyResolver from flask_cors import CORS app = connexion.App("myApp") CORS(app.app)
Following up with the Scripting In Rhino Python series of articles, here is a useful snippet of code that automates switching units on a Rhino document.
This script basically switches the units of the current document between meters and millimeters. The important function is rs.UnitSystem(), which returns the current unit measure — or sets it if we give parameters to the function.
import rhinoscriptsyntax as rs if rs.UnitSystem() == 2: # Current unit is mm, Switch to m rs.UnitSystem(4, False, True) else: # Current unit is m, switch to mm rs.UnitSystem(2, False, True)
This article is part of a series of posts about efficient architectural methods, workflows and tools, titled Getting Architecture Done.
If you want to be notified when any other articles of the same series are posted, go ahead an subscribe here.
This is a little introduction to Python Scripting in Rhino for beginners.
In previous versions of Rhino, scripting was possible in RhinoScript with VBScript. In Rhino 5.0, Python has been introduced—a powerful object oriented scripting language.
How do I start? Open Rhino 5.0 and type the command EditPythonScript. This will open the Rhino Python Editor's window. On the left, you have the python, rhinoscriptsyntax, scriptcontext and Rhino libraries. On the right, script tabs appear in which you can create new scripts or edit existing ones.
Here are a few examples using really basic features of the rhinoscriptsyntax library.
Let's get hands on and try writing and running a simple script.
Just click the New File icon and write the following text. To comment code in Python, the dash (#) is used, this tells the python's code interpreter to ignore those lines.
# The next line will log Hello, Python on the console print "Hello, Python!"
Now, press the green play button or F5 to make the code run. If everything is right, you will be able to see on the bottom of the window the message -Hello, Python!- displayed on the console.
The above code just runs python code, without using the library that Rhino offers to interact with the program. The following example will import the RhinoScript library into the python script, and it will then add a Point and a Line to our current Rhino document.
# Import the RhinoScript library to python as the variable rs import rhinoscriptsyntax as rs # Add a Point at cartesian coordinates (x, y, z) = (10, 10, 3) rs.AddPoint([10,10,3]) # Add a Line from (0, 0, 0) to (3, -2, 0) rs.AddLine([0,0,0], [3,-2,0])
Now, we will create a loop which will add different points to your document. I also introduced here the function rs.EnableRedraw(BOOL), that increases performance when drawing a lot of items into the document by not allowing Rhino to update the view until we reactivate that feature.
# Import the RhinoScript library to python as the variable rs import rhinoscriptsyntax as rs # Disable Redraw so Rhino doesn't update every time it creates a new geometry rs.EnableRedraw(False) # Definition of variables for our loop/range # Value at which the loop starts from start = 0 # Value until which the loop goes to to = 10 # Step value of the loop step = 1 # Loop for i in range(start,to,step): rs.AddPoint([i,0,0]) # Enable Redraw so Rhino draws the new geometry rs.EnableRedraw(True);
The loop runs from the value 0 to 10, with a step of 1 in between each of the cycles. This basically means that the Python scripts will add into our Rhino document the points that range from [0,0,0] to [10,0,0], by adding 1 to the x value of the point each step of the loop and attaching that point into the document. You can try editing the values from, to and step to see what happens.
This article was part of a series of posts about architectural methods, workflows and tools, titled Getting Architecture Done.
In the future, I will share more scripts. I hope this serves as an introduction to see the most basic things you can do with Python in Rhino. If you come from another programming language or don't know how to program, trying small code snippets is a good way to start. Copy and paste code that others have created and try modifying small parts of it.
Also, the reference guide of Python in Rhino 5.0 shows all the functions that rhinoscriptsyntax offers, to see what Rhino allows you to do, and it is accessible through the Help menu in the EditPythonScript window.
If you found this article useful, please share it with people you think may be interested. And tell me what you think!