Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of executing scripts in Python

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail what the Python script execution methods are, and the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Shell script is called in Python. The common functions are os.system, os.popen () and subprocess.Popen ().

Os.system method

Syntax: os.system (cmd)

Os.system () execution mainly executes: fork () gives a child process; the child process calls exec () to execute the command.

Example 1:

> import os > os.system ('dir D:\ Python')

The execution succeeds and 0 is returned.

Example 2:

Import osres = os.system ('ping www.baidu.com-n 3') if res = = 0:print (' successful') else:print ('failed')

Execution result:

Note:

1) .os.system () executes the cmd instruction. A result of 0 indicates success and 1 indicates failure.

2). Os.system () cannot get the content output in cmd.

3) .os.system () calls the external system command, returns the command result code, and cannot get the output result of the command execution.

Os.popen method

Syntax: popen (cmd, mode='r', buffering =-1)

Parameters:

Cmd: the command to execute. Mode: the mode in which the file is opened, which defaults to 'ringing' and uses the same as open (). Buffering: (optional), 0 table without buffering; 1 table row buffering;-1 table default buffer value

The os.popen () method opens a pipe and returns a file object to which the pipe is connected. The successful execution returns the result read in the file object and does not return the status code. Execution failed and an error message was returned. And the returned result can be assigned to a variable to facilitate the processing of the program.

Example 1:

File content: d:\ Python\ test.py

Print ('popen () Test')

File content: d:\ Python\ test2.py

Res = os.popen (ruddy:\ Python\ test.py', mode='r') res1 = res.read () # the returned result is assigned to a variable to facilitate the processing of the program print (res1) print (type (res1)) # returns strres.close ()

Python D:\ Python\ test2.py execution result:

Subprocess module

The functions implemented by os.system and os.popen can be implemented in the subprocess module and are recommended. And the subprocess module can also call external system commands to create new child processes. When subprocess executes system commands, it will not let the main process execute, but the main process will open up fork () to execute a child process, which will not affect the running of the main process.

The subprocess module mainly has call () and Popen () functions.

3.1 subprocess.Popen () function

Syntax:

Subprocess.Popen (args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)

Args: the external system command to be invoked.

Bufsize: the default value is 0, which means no cache; a value of 1 indicates row cache; other positive numbers indicate the size of the cache used; a negative number of-1 indicates the use of the system default cache size.

Stdin, stdout, stderr: stand for standard input, standard output, and standard error, respectively. Its values are PIPE, file descriptor, None, and so on. The default value is None, which means that it is inherited from the parent process.

When the parameter value in shell:Linux is False, the corresponding program is executed on Linux by calling os.execvp. When True, the system shell is called directly on the Linux to execute the program. The parameter shell in Windows is set to true, and the program will be executed through shell.

Cwd: sets the current directory of the child process.

Env:env is the dictionary type that specifies the environment variable of the child process. The default value is None, which means that the environment variables of the child process will be inherited from the parent process.

Subprocess.PIPE: when creating a Popen object, subprocess.PIPE can initialize the stdin, stdout, or stderr parameters that represent the standard stream that communicates with the child process. The execution result is thrown into the pipeline (shared memory space, which is used for sharing between processes).

Example 1:

Cmd = 'ipconfig | findstr "192.168.1.128"' p = subprocess.Popen (cmd, shell=True, stdout=subprocess.PIPE) # throws the correct execution result into the pipeline. Res = p.stdout.read (). Decode ('gbk') # the main process goes to the pipeline to get the correct stdout result and converts the bytes type of the obtained result. Print (res) print (type (res))

The subprocess.Popen () method compares to os.popen (), where the output obtained by os.popen () is directly readable, while the output obtained by subprocess.Popen () is in binary form with newline characters.

3.2 subprocess.call () function

Call the external system command and return the execution result code. The function is similar to os.system (cmd). 0 indicates successful execution, and return 1 indicates failure.

Example 2:

Import subprocessres = subprocess.call ('ping www.baidu.com', shell=True) print (' > > ping www.baidu.com') print ('Test res:', res)

Results:

On the Python script execution methods are shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report