Categories
Python Answers

How to check which version of Python is running in a script?

Sometimes, we want to check which version of Python is running in a script.

In this article, we’ll look at how to check which version of Python is running in a script.

How to check which version of Python is running in a script?

To check which version of Python is running in a script, we can use the sys.version and sys.version_info properties.

For instance, we write:

import sys

print(sys.version)
print(sys.version_info)

sys.version provides basic version info.

And it returns data like:

3.8.12 (default, Sep 10 2021, 00:16:05) 
[GCC 7.5.0]

sys.version_info provides more detailed version info.

It returns data like:

sys.version_info(major=3, minor=8, micro=12, releaselevel='final', serial=0)

Conclusion

To check which version of Python is running in a script, we can use the sys.version and sys.version_info properties.

Categories
Python Answers

How to use threading in Python?

Sometimes, we want to use threading in Python.

In this article, we’ll look at how to use threading in Python.

How to use threading in Python?

To use threading in Python, we can use the Pool class from the multiprocessing.dummy module.

For instance, we write:

import urllib.request
from multiprocessing.dummy import Pool as ThreadPool

urls = [
    'http://www.python.org', 'http://www.python.org/about/',
    'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
    'http://www.python.org/doc/', 'http://www.python.org/getit/'
]

pool = ThreadPool(4)
results = pool.map(urllib.request.urlopen, urls)
pool.close()
pool.join()

We import the Pool class as ThreadPool.

Then we create a thread pool with 4 worker threads in it with the ThreadPool class.

Next, we call pool.map with the urllib.request.urlopen function and urls to call urllib.request.urlopen with the entries in urls and return the results.

Then we call pool.close to close the pool and wait for the work to finish with pool.join.

Conclusion

To use threading in Python, we can use the Pool class from the multiprocessing.dummy module.

Categories
Python Answers

How to pretty print a JSON file with Python?

Sometimes, we want to pretty print a JSON file with Python.

In this article, we’ll look at how to pretty print a JSON file with Python.

How to pretty print a JSON file with Python?

To pretty print a JSON file with Python, we can use the json.dumps method with the indent and sort_keys parameters.

For instance, we write:

import json

your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(json.dumps(parsed, indent=2, sort_keys=True))

We call json.loads with your_json to load the JSON string into a dictionary.

Then we call json_dumps with the parsed JSON and indent set to 2 to indent each level with 2 spaces.

sort_keys is set to True to sort the keys alphabetically.

Therefore,

[
  "foo",
  {
    "bar": [
      "baz",
      null,
      1.0,
      2
    ]
  }
]

is printed.

Conclusion

To pretty print a JSON file with Python, we can use the json.dumps method with the indent and sort_keys parameters.

Categories
Python Answers

How to profile a Python script?

Sometimes, we want to profile a Python script.

In this article, we’ll look at how to profile a Python script.

How to profile a Python script?’

To profile a Python script, we can use the cProfile.run method.

For instance, we write:

import cProfile


def hello():
    print('hello')


cProfile.run('hello()')

We put the code into the string that we call cProfile.run with to profile the hello function’s execution.

Then we get output like:

         5 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 main.py:4(hello)
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {built-in method builtins.print}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

printed on the screen.

Conclusion

To profile a Python script, we can use the cProfile.run method.

Categories
Python Answers

How to import a module given the full path in Python?

Sometimes, we want to import a module given the full path in Python.

In this article, we’ll look at how to import a module given the full path in Python.

How to import a module given the full path in Python?

To import a module given the full path in Python, we can use the importlib.util module.

For instance, if we have the following module:

foo.py:

def hello():
    print('hello')

Then if main.py is in the same folder and we want to use foo.py in it.

We write:

import importlib.util

spec = importlib.util.spec_from_file_location("module.name", "./foo.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.hello()

We call importlib.util.spec_from_file_location with 'module.name' and './foo.py‘ to import the module.

Then we call importlib.util.module_from_spec to import the returned spec object.

Next, we call spec.loader.exec_module with the imported foo module to load it.

And then we call foo.hello to run the hello function in foo.py.

Therefore, 'hello' should be printed.

Conclusion

To import a module given the full path in Python, we can use the importlib.util module.