python - creating a "scripting" system

  • Last Update :
  • Techknowledgy :

The following is a step-by-step guide for setting up your developer environment and getting you started using Python for scripting and automating file system operations on Windows.,Hope you learned a few fun things about using Python scripts for automating basic systems administration tasks. There is, of course, a ton more to know, but we hope this got you started on the right foot. We've shared a few additional resources to continue learning below.,Once Python has completed the downloading and installation process, open Windows PowerShell using the Start menu (lower left Windows icon). Once PowerShell is open, enter Python --version to confirm that Python3 has been installed on your machine.,Once Python has completed the downloading and installation process, open Windows PowerShell using the Start menu (lower left Windows icon). Once PowerShell is open, enter Python --version to confirm that Python3 has been installed on your machine.

Create a few directories to use with our example script:

mkdir food, food\ fruits, food\ fruits\ apples, food\ fruits\ oranges, food\ vegetables

Create a few files within those directories to use with our script:

new - item food\ fruits\ banana.txt, food\ fruits\ strawberry.txt, food\ fruits\ blueberry.txt, food\ fruits\ apples\ honeycrisp.txt, food\ fruits\ oranges\ mandarin.txt, food\ vegetables\ carrot.txt

Create a new python file in your python-scripts directory:

mkdir src
new - item src\ list - directory - contents.py

Paste the following code into your list-directory-contents.py file and then select save:

import os

root = os.path.join('..', 'food')
for directory, subdir_list, file_list in os.walk(root):
   print('Directory:', directory)
for name in subdir_list:
   print('Subdirectory:', name)
for name in file_list:
   print('File:', name)
print()

Open the VS Code integrated terminal (Ctrl+`, using the backtick character) and enter the src directory where you just saved your Python script:

cd src

Run the script in PowerShell with:

python3.\list - directory - contents.py

You should see output that looks like this:

Directory: ..\food
Subdirectory: fruits
Subdirectory: vegetables

Directory: ..\food\ fruits
Subdirectory: apples
Subdirectory: oranges
File: banana.txt
File: blueberry.txt
File: strawberry.txt

Directory: ..\food\ fruits\ apples
File: honeycrisp.txt

Directory: ..\food\ fruits\ oranges
File: mandarin.txt

Directory: ..\food\ vegetables
File: carrot.txt

Suggestion : 2

To start with the basics, here is a Hello World script in Python:

$ cat hello.py3
#!/usr/bin / python3
print("hello world!")
$ python3 hello.py3
hello world!
   $ echo $ ?
   0

Examine the Python interpreter via the rpm command-line interface (CLI) tool. This shows the interpreter is based on version 3.6:

$ rpm - qf / usr / bin / python3
python36 - 3.6 .8 - 38. module + el8 .5 .0 + 12207 + 5 c5719bc.x86_64
$ ll / usr / bin / python3
lrwxrwxrwx.1 root root 25 Feb 3 2020 / usr / bin / python3 - > /etc/alternatives / python3

After running the Hello World script, verify a clean exit by echoing the previous command's return code:

$ echo $ ?
   0

So, using:

greeting(last_name, mystate, first_name)

would make the output:

Hello, Gervase North Carolina!How is the weather in Peter ?

Suggestion : 3

Often, the point of writing a reusable module is so that you can take some of the code and use it over and over again in a new script. So practice that by writing another script that uses one of the functions. See Example 1-6.,When we look at this documentation, “Docstring” is the official term, we see an example of the way to use subprocess.call and a description of what it does.,If you are coming from a shell programming/scripting background, though, don’t worry at all. You, too, can learn Python quite easily. You need only motivation, curiosity, and determination, the same factors that led you to pick up this book and look at the introduction in the first place.,When there is no control flow, or main function, then all of the code gets executed immediately when it is imported. This may be OK for a one-off script, but if you plan to create reusable tools, and you should, then it is a good practice to create functions that encapsulate specific actions, and then have a main function that executes the whole program.

#!/bin/bash

for a in 1 2;
do
   for b in a b;
do
   echo "$a $b"
done
done

Many of the benefits that we see in Python stem from the central philosophy of Python. When you type import this at a Python prompt, you will see The Zen of Python by Tim Peters. Here it is:

In[1]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren 't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one--and preferably only one--obvious way to do it.
Although that way may not be obvious at first unless you 're Dutch.
Now is better than never.
Although never is often better than * right * now.
If the implementation is hard to explain, it 's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea--
let 's do more of those!

Once you have installed IPython and have an IPython shell prompt, it should look something like this:

[ngift @Macintosh - 7][H: 10679][J: 0] # ipython
Python 2.5 .1(r251: 54863, Jan 17 2008, 19: 35: 17)
Type "copyright", "credits"
or "license"
for more information.

IPython 0.8 .2--An enhanced Interactive Python. ?
   - > Introduction and overview of IPython 's features. %
   quickref - > Quick reference.
help - > Python 's own help system.
object ? - > Details about 'object'. ? object also works, ?? prints more.

In[1]:

In your Python terminal, type in the following:

In[1]: print "I can program in Python"
I can program in Python

In your Bash terminal, type in the following:

[ngift @Macintosh - 7][H: 10688][J: 0] # echo "I can program in Bash"
I can program in Bash

If you spend a lot of your day typing commands into a terminal, then you are used to executing statements and, perhaps, redirecting the output to a file or to another Unix command. Let’s look at the way we would execute a command in Bash and then compare that to the way it works in Python. In the Bash terminal, type the following:

[ngift @Macintosh - 7][H: 10701][J: 0] # ls - l / tmp /
   total 0 -
   rw - r--r--1 ngift wheel 0 Apr 7 00: 26 file.txt

In the Python terminal, type the following:

In[2]: import subprocess

In[3]: subprocess.call(["ls", "-l ", "/tmp/"])
total 0
   -
   rw - r--r--1 ngift wheel 0 Apr 7 00: 26 file.txt
Out[3]: 0

The Bash example shouldn’t need any explanation as it is a simple ls command, but if you have never seen Python code before, the Python example probably looks a bit strange. You might be thinking, “What the heck is this import subprocess thing?” One of the powerful features of Python is its ability to import modules or other files that contain code and reuse them in a new program. If you are familiar with “sourcing” a file in Bash, then you will recognize some similarities. In this particular situation, all that is important to know is that you import the subprocess and use it in the syntax that is shown. We will get into the particulars of how subprocess and import work later, but for now, ignore why it works and copy the code:

subprocess.call(["some_command", "some_argument", "another_argument_or_path"])

Now if you run this script, you will get the exact same output that you would get if you ran ls -ls from the command line:

[ngift @Macintosh - 7][H: 10746][J: 0] #. / pyls.py
total 8
   -
   rwxr - xr - x 1 ngift staff 115 Apr 7 12: 57 pyls.py
6._
#!/usr/bin/env python

#A System Information Gathering Script
import subprocess

#Command 1
uname = “uname”
uname_arg = “-a”
print "Gathering system information with %s command:\n" % uname
subprocess.call([uname, uname_arg])

#Command 2
diskspace = "df"
diskspace_arg = "-h"
print "Gathering diskspace information %s command:\n" % diskspace
subprocess.call([diskspace, diskspace_arg])
#!/usr/bin/env python

#Python wrapper
for the ls command

import subprocess

subprocess.call(["ls", "-l"])
#!/usr/bin/env python

#A System Information Gathering Script
import subprocess

#Command 1
uname = “uname”
uname_arg = “-a”
print "Gathering system information with %s command:\n" % uname
subprocess.call([uname, uname_arg])

#Command 2
diskspace = "df"
diskspace_arg = "-h"
print "Gathering diskspace information %s command:\n" % diskspace
subprocess.call([diskspace, diskspace_arg])
#!/usr/bin/env bash

#A System Information Gathering Script

#Command 1
UNAME = "uname -a"
printf“ Gathering system information with the $UNAME command: \n\ n "
$UNAME

#Command 2
DISKSPACE = "df -h"
printf "Gathering diskspace information with the $DISKSPACE command: \n\n"
$DISKSPACE

Suggestion : 4

A script is used to automate certain tasks in a program. It can run by itself and it is less code intensive whereas modules in python is referred as a library which can not run by its own. It needs to get imported in order to use it. In case you want to know more about python scripting and learn how to write scripts, you can refer this video: https://youtu.be/9F6zAuYtuFw or you can join Python online course today.,A Python script normally can be full of functions that can be imported as a library of functions in other scripts, or a python script can be a command that runs in Rhino.,A Python script is a collection of commands in a file designed to be executed like a program. Often a script first contains a set of function definitions and then has the main program that might call the functions. .,To create a module just save the code you want in a file with the file extension .py :

The key is to add these statements to the end of the file:

if __name__ == '__main__':
   CreateCircle() # Put the a call to the main
function in the file