How to use Python shell script
1. What is sh
SH is a unique subprocess wrapper that can dynamically map your system programs to Python functions. SH helps you write Shell scripts in Python, which not only supports all the functions of Bash (simple command invocation, simple pipe transmission), but also takes into account the flexibility of Python.
SH is a mature subprocess interface in Python that allows you to call any system program as if it were a function. That is, SH lets you invoke almost any command that can be run from a login shell.
More importantly, you can capture and parse the output of your commands more easily.
2. Usage steps
1. Installation
Install sh
pip install sh
through the pip command
#2.Use the exampleStart and The easiest way to run is to import sh directly or import the command you need from sh. The command can then be used like a Python function. For example, pass parameters, capture the output and use the output in python. See the code example below for details# get interface information import sh print sh.ifconfig("eth0") from sh import ifconfig print ifconfig("eth0") # print the contents of this directory print ls("-l") # substitute the dash for an underscore for commands that have dashes in their names sh.google_chrome("http://google.com")
# 子命令
>>> from sh import git, sudo
>>> print(git.branch("-v"))
>>> print(git("branch", "-v"))
>>> print(sudo.ls("/root"))
>>> print(sudo("/bin/ls", "/root"))
# with 环境
>>> with sh.contrib.sudo(_with=True):
print(ls("/root"))
# _with=True 关键字告诉命令它正处于 with 环境中, 以便可以正确地运行.
#将多个参数传递给命令时,每个参数必须是一个单独的字符串:
from sh import tar
tar("cvf", "/tmp/test.tar", "/my/home/directory/")
# 这将不起作用:
from sh import tar
tar("cvf /tmp/test.tar /my/home/directory")
Copy after login
3. Use sh to execute the commandThe command is called just like a function. But "It should be noted that these are not real Python functions. What is actually run is the corresponding binary command in the system. Just like Bash, it runs dynamically on the system by parsing PATH.Because of this, Python has very good support for Shell commands, and all commands on the system can be easily run through Python." Many programs have their own subsets of commands, such as git (branch, sign out). sh handles subcommands through attribute access. # 子命令 >>> from sh import git, sudo >>> print(git.branch("-v")) >>> print(git("branch", "-v")) >>> print(sudo.ls("/root")) >>> print(sudo("/bin/ls", "/root")) # with 环境 >>> with sh.contrib.sudo(_with=True): print(ls("/root")) # _with=True 关键字告诉命令它正处于 with 环境中, 以便可以正确地运行. #将多个参数传递给命令时,每个参数必须是一个单独的字符串: from sh import tar tar("cvf", "/tmp/test.tar", "/my/home/directory/") # 这将不起作用: from sh import tar tar("cvf /tmp/test.tar /my/home/directory")
from sh import git
# resolves to "git branch -v"
print(git.branch("-v"))
print(git("branch", "-v")) # the same command
Copy after login
4. Keyword Arguments Keyword arguments also work as you would expect: they are replaced with command line argument options. from sh import git # resolves to "git branch -v" print(git.branch("-v")) print(git("branch", "-v")) # the same command
# Resolves to "curl http://duckduckgo.com/ -o page.html --silent"
sh.curl("http://duckduckgo.com/", o="page.html", silent=True)
# If you prefer not to use keyword arguments, this does the same thing
sh.curl("http://duckduckgo.com/", "-o", "page.html", "--silent")
# Resolves to "adduser amoffat --system --shell=/bin/bash --no-create-home"
sh.adduser("amoffat", system=True, shell="/bin/bash", no_create_home=True)
# or
sh.adduser("amoffat", "--system", "--shell", "/bin/bash", "--no-create-home")
Copy after login
5. Find command "Which" finds the full path of the program, and returns None if it does not exist. This command is one of the few that is actually implemented as a Python function, and therefore does not rely on an actual "which" binary. # Resolves to "curl http://duckduckgo.com/ -o page.html --silent" sh.curl("http://duckduckgo.com/", o="page.html", silent=True) # If you prefer not to use keyword arguments, this does the same thing sh.curl("http://duckduckgo.com/", "-o", "page.html", "--silent") # Resolves to "adduser amoffat --system --shell=/bin/bash --no-create-home" sh.adduser("amoffat", system=True, shell="/bin/bash", no_create_home=True) # or sh.adduser("amoffat", "--system", "--shell", "/bin/bash", "--no-create-home")
print sh.which("python") # "/usr/bin/python" print sh.which("ls") # "/bin/ls" if not sh.which("supervisorctl"): sh.apt_get("install", "supervisor", "-y")
# The idea here is that now every call to ls will have the “-la” arguments already specified. from sh import ls ls = ls.bake("-la") print(ls) # "/usr/bin/ls -la" # resolves to "ls -la /" print(ls("/"))
# Without baking, calling uptime on a server would be a lot to type out: serverX = ssh("myserver.com", "-p 1393", "whoami") # To bake the common parameters into the ssh command myserver = sh.ssh.bake("myserver.com", p=1393) print(myserver) # "/usr/bin/ssh myserver.com -p 1393"
# resolves to "/usr/bin/ssh myserver.com -p 1393 tail /var/log/dumb_daemon.log -n 100" print(myserver.tail("/var/log/dumb_daemon.log", n=100)) # check the uptime print myserver.uptime() 15:09:03 up 61 days, 22:56, 0 users, load average: 0.12, 0.13, 0.05
The above is the detailed content of How to use Python shell script. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

Question: How to view the Redis server version? Use the command line tool redis-cli --version to view the version of the connected server. Use the INFO server command to view the server's internal version and need to parse and return information. In a cluster environment, check the version consistency of each node and can be automatically checked using scripts. Use scripts to automate viewing versions, such as connecting with Python scripts and printing version information.

Navicat's password security relies on the combination of symmetric encryption, password strength and security measures. Specific measures include: using SSL connections (provided that the database server supports and correctly configures the certificate), regularly updating Navicat, using more secure methods (such as SSH tunnels), restricting access rights, and most importantly, never record passwords.
