Fleta  Dickens

Fleta Dickens

1672710327

How to Run and Pass information To A Python Script

Running your Python scripts is an important step in the development process because it is in this manner that you’ll get to find out if your code works as you intended it to. Also, it is often the case that we would need to pass information to the Python script for it to function.

In this tutorial, you will discover various ways of running and passing information to a Python script.

After completing this tutorial, you will know:

  • How to run a Python script using the command-line interface, the Jupyter Notebook, or an Integrated Development Environment (IDE) 
  • How to pass information to a Python script using the  sys.argv  command by hard-coding the input variables in the Jupyter Notebook or through the interactive use of the input()  function. 

 

Kick-start your project with my new book Python for Machine Learning, including step-by-step tutorials and the Python source code files for all examples.

Let’s get started.

Tutorial Overview

This tutorial is divided into two parts; they are:

  • Running a Python Script
    • Using a Command-Line Interface
    • Using the Jupyter Notebook
    • Using an Integrated Development Environment (IDE)
  • Python Input

Running a Python Script:

Using a Command-Line Interface

The command-line interface is used extensively for running Python code. 

Let’s test a few commands by first opening up a Command Prompt or Terminal window, depending on the operating system that you are working on. 

Typing the  python command in your command-line interface will initiate a Python interactive session. You will see that a message appears informing you of the Python version that you are using. 


Python 3.7.4 (default, Aug 13 2019, 15:17:50) 
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.

Any statements you write in your command-line interface during an interactive session will be executed immediately. For example, typing out 2 + 3 returns a value of 5:

2 + 3
5

Using an interactive session in this manner has its advantages because you can test out lines of Python code easily and quickly. However, it is not the ideal option if we are more interested in writing lengthier programs, as would be the case if we are developing a machine learning algorithm. The code also disappears once the interactive session is terminated. 

An alternative option would be to run a Python script. Let’s start with a simple example first. 

In a text editor (such as Notepad++, Visual Studio Code, or Sublime Text), type the statement  print("Hello World!")  and save the file to test_script.py or any other name of your choice as long as you include a .py extension. 

Now, head back to your command-line interface and type the python command, followed by the name of your script file. Before you do so, you might need to change the path to point to the directory that contains the script file. Running the script file should then produce the following output:

python test_script.py
Hello World!

Let’s now write a script file that loads a pre-trained Keras model and outputs a prediction for this image of a dog. It is often the case that we would also need to pass information to the Python script in the form of command-line arguments. For this purpose, we will be using the  sys.argv  command to pass to the script the image path and the number of top guesses to return. We could have as many input arguments as the code requires, in which case we would keep on reading the inputs from the argument list.  

The script file that we will be running now contains the following code:

import sys
import numpy as np
from tensorflow.keras.applications import vgg16
from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
 
# Load the VGG16 model pre-trained on the ImageNet dataset
vgg16_model = vgg16.VGG16(weights='imagenet')
 
# Read the command-line argument passed to the interpreter when invoking the script
image_path = sys.argv[1]
top_guesses = sys.argv[2]
 
# Load the image, resized according to the model target size
img_resized = image.load_img(image_path, target_size=(224, 224))
 
# Convert the image into an array
img = image.img_to_array(img_resized) 
 
# Add in a dimension
img = np.expand_dims(img, axis=0) 
 
# Scale the pixel intensity values
img = preprocess_input(img) 
 
# Generate a prediction for the test image
pred_vgg = vgg16_model.predict(img)
 
# Decode and print the top 3 predictions
print('Prediction:', decode_predictions(pred_vgg, top=int(top_guesses)))

In the above code, we read the command line arguments using sys.argv[1] and sys.argv[2] for the first two arguments. We can run the script by making use of the python command followed by the name of the script file and further passing it as arguments for the image path (after the image has been saved to the disk) and the number of top guesses that we would like to predict:

python pretrained_model.py dog.jpg 3

Here, pretrained_model.py is the name of the script file, and the dog.jpg image has been saved into the same directory that also contains the Python script. 

The generated top three guesses are the following:

Prediction: [[('n02088364', 'beagle', 0.6751468), ('n02089867', 'Walker_hound', 0.1394801), ('n02089973', 'English_foxhound', 0.057901423)]]

But there can be more in the command line. For example, the following command line will run the script in “optimized” mode, in which the debugging variable __debug__ is set to False, and assert statements are skipped:

python -O test_script.py

And the following is to launch the script with a Python module, such as the debugger:

python -m pdb test_script.py

We will have another post about the use of the debugger and profilers.

Using Jupyter Notebook

Running a Python script from the command-line interface is a straightforward option if your code generates a string output and not much else. 

However, when we are working with images, it is often desirable to generate a visual output too. We might be checking the correctness of any pre-processing applied to the input image before feeding it into a neural network or visualizing the result that the neural network produces. The Jupyter Notebook offers an interactive computing environment that can help us achieve this.

One way of running a Python script through the Jupyter Notebook interface is to simply add the code to a “cell” in the notebook. But this means your code stays inside the Jupyter notebook and cannot be accessed elsewhere, such as using the command line as above. Another way is to use the run magic command, prefixed by the  %  character. Try typing the following code into a cell in Jupyter Notebook:

%run pretrained_model.py dog.jpg 3

Here, we are again specifying the name of the Python script file as pretrained_model.py, followed by the image path and the number of top guesses as the input arguments. You will see that the top three predictions are printed beneath the cell that produced this result. 

Now, let’s say that we would like to display the input image in order to check that it has been loaded according to the model target size. For this purpose, we will modify the code slightly as follows and save it into a new Python script, pretrained_model_image.py:

import sys
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import vgg16
from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
 
# Load the VGG16 model pre-trained on the ImageNet dataset
vgg16_model = vgg16.VGG16(weights='imagenet')
 
# Read the arguments passed to the interpreter when invoking the script
image_path = sys.argv[1]
top_guesses = sys.argv[2]
 
# Load the image, resized according to the model target size
img_resized = image.load_img(image_path, target_size=(224, 224))
 
# Convert the image into an array
img = image.img_to_array(img_resized)
 
# Display the image to check that it has been correctly resized
plt.imshow(img.astype(np.uint8))
 
# Add in a dimension
img = np.expand_dims(img, axis=0) 
 
# Scale the pixel intensity values
img = preprocess_input(img) 
 
# Generate a prediction for the test image
pred_vgg = vgg16_model.predict(img)
 
# Decode and print the top 3 predictions
print('Prediction:', decode_predictions(pred_vgg, top=int(top_guesses)))

Running the newly saved Python script through the Jupyter Notebook interface now displays the resized 224×224 pixel image, in addition to printing the top three predictions:

%run pretrained_model_image.py dog.jpg 3

Running a Python Script in Jupyter Notebook

 

Alternatively, we can trim down the code to the following (and save it to yet another Python script, pretrained_model_inputs.py):

# Load the VGG16 model pre-trained on the ImageNet dataset
vgg16_model = vgg16.VGG16(weights='imagenet')
 
# Load the image, resized according to the model target size
img_resized = image.load_img(image_path, target_size=(224, 224))
 
# Convert the image into an array
img = image.img_to_array(img_resized) 
 
# Display the image to check that it has been correctly resized
plt.imshow(img.astype(np.uint8))
 
# Add in a dimension
img = np.expand_dims(img, axis=0) 
 
# Scale the pixel intensity values
img = preprocess_input(img) 
 
# Generate a prediction for the test image
pred_vgg = vgg16_model.predict(img)
 
# Decode and print the top 3 predictions
print('Prediction:', decode_predictions(pred_vgg, top=top_guesses))

And define the input variables in one of the cells of the Jupyter Notebook itself. Running the Python script in this manner would require that we also make use of the  -i  option after the  %run  magic:

%run -i pretrained_model_inputs.py

 

Running a Python Script in Jupyter Notebook

 

The advantage of doing so is to gain easier access to variables inside the Python script that can be defined interactively. 

As your code grows, combining the use of a text editor with Jupyter Notebook could provide a convenient way forward: the text editor can be used to create Python scripts, which store code that can be reused, while the Jupyter Notebook provides an interactive computing environment for easier data exploration. 

Using an Integrated Development Environment (IDE)

Another option is to run the Python script from an IDE. This requires that a project is created first, and the Python script with a .py extension is added to it. 

If we had to consider PyCharm or Visual Studio Code as the IDE of choice, this would require that we create a new project and subsequently choose the version of Python interpreter that we would like to work with. After adding the Python script to the newly created project, this can be run to generate an output. The following is a screenshot of running Visual Studio Code on macOS. Depending on the IDE, there should be an option to run the code with or without the debugger.

Python Input

We have, so far, considered the options of passing information to the Python script using the sys.argv  command or by hard-coding the input variables in Jupyter Notebook before running the script. 

Another option is to take input from the user through the input()  function. 

Consider the following code:

import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import vgg16
from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
 
# Load the VGG16 model pre-trained on the ImageNet dataset
vgg16_model = vgg16.VGG16(weights='imagenet')
 
# Ask the user for manual inputs
image_path = input("Enter image path: ")
top_guesses = input("Enter number of top guesses: ")
 
# Load the image, resized according to the model target size
img_resized = image.load_img(image_path, target_size=(224, 224))
 
# Convert the image into an array
img = image.img_to_array(img_resized)
 
# Add in a dimension
img = np.expand_dims(img, axis=0) 
 
# Scale the pixel intensity values
img = preprocess_input(img) 
 
# Generate a prediction for the test image
pred_vgg = vgg16_model.predict(img)
 
# Decode and print the top 3 predictions
print('Prediction:', decode_predictions(pred_vgg, top=int(top_guesses)))

Here, the user is prompted to manually enter the image path (the image has been saved into the same directory containing the Python script and, hence, specifying the image name is sufficient) and the number of top guesses to generate. Both input values are of type string; however, the number of top guesses is later cast to an integer when this is used. 

No matter if this code is run in the command-line interface, in Jupyter Notebook, or in a Python IDE, it will prompt the user for the required inputs and subsequently generate the number of predictions that the user asks for. 

Further Reading

This section provides more resources on the topic if you are looking to go deeper.

Books

Summary

In this tutorial, you discovered various ways of running and passing information to a Python script.

Specifically, you learned:

  • How to run a Python script using the command-line interface, the Jupyter Notebook, or an Integrated Development Environment (IDE)
  • How to pass information to a Python script using the sys.argv  command by hard-coding the input variables in Jupyter Notebook or through the interactive use of the input()  function

Do you have any questions?

Ask your questions in the comments below, and I will do my best to answer.

Original article sourced at: https://machinelearningmastery.com

#python 

What is GEEK

Buddha Community

How to Run and Pass information To A Python Script
Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Ray  Patel

Ray Patel

1623336480

How to run Python Scripts?

You should probably know how to run Python scripts if you are familiar with Python.

Why should you read this article? And another chance that you don’t know how to run Python scripts as you are not familiar with them. It’s definitely for you. Is this only for you? No, both who are familiar and who are not with Python can get something new in this article. Without further ado let’s jump into the article.

Before going into the execution part of the tutorial, we need to have installed Python on our systems.

Open a text editor and create a Python script to use throughout this tutorial. You can use the following script of adding two numbers.

a, b = list(map(int, input().split()))
print(a + b)

#development #python #python scripts #how to run python scripts #way to run python

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Ray  Patel

Ray Patel

1623225360

How to Run bash scripts Using Python?

If you are using Linux, then you would definitely love the shell commands.

And if you are working with Python, then you may have tried to automate things. That’s a way to save time. You may also have some bash scripts to automate things.

Python is handy to write scripts than bash. And managing Python scripts are easy compared to bash scripts. You will find it difficult to maintain the bash scripts once it’s growing.

But what if you already have bash scripts that you want to run using Python?

Is there any way to execute the bash commands and scripts in Python?

Yeah, Python has a built-in module called subprocess which is used to execute the commands and scripts inside Python scripts. Let’s see how to execute bash commands and scripts in Python scripts in detail.

#development #python #how to run bash scripts using python #shell script from python #bash script #shell=

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development