. Popen (["Cat", "/etc/passwd"]) Root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:X:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncin [30]: Subprocess.Popen ("cat/etc/passwd")---------------------------------------------------------------------------OSError Traceback (most recent)The first one is OK. The second way is not OK. What is the reason for this?Main time Shell
A simple comparison:
http://blog.csdn.net/monkey_d_meng/article/details/6173055
(done)
Shell Programming Basics:
Http://wiki.ubuntu.org.cn/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#if_.E8.AF.AD_.E5.8F.A5
Python Learning:
Official website: https://www.python.org/
Official document Chinese version: Http://www.pythondoc.com/pythontutorial3/index.html (pending)
Super
1. When a shell script executes a Python script, it needs to use the return value of the Python script to determine the command to be executed by the subsequent program.Example: There are two py programs hello.pyCopy CodeThe code is as follows:def main ():Print "Hello"If __name__== ' __main__ ':Main ()world.pydef main ():Print "Hello"If __name__== ' __main__ ':Ma
Nonsense not to say, direct (the first one is the script written by Python, the second and third is the shell):650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/54/93/wKiom1SGpk6Ttl_MAAVPK2KJQoE175.jpg "title=" Python and shell efficiency comparison. png "alt=" wkiom1sgpk6ttl_maavpk2kjqoe175.jpg "/>The file is
Http://blog.sina.com.cn/s/blog_53d874320102vdvu.html
Log in with the Python SSH module and execute shell commands on the remote machine
(in CentOS 7 The environmental test was successful, the Redhat series should be compatible.) )
Install the necessary modules first
# yum Install Python-dev
# yum Install Python-devel
This article mainly introduces Python and shell variable transfer methods, using environment variables, pipelines and other methodsPython--Shell:1. Environment variablesCopy CodeThe code is as follows:Import OSvar=123 or var= ' 123 'Os.environ[' var ']=str (Var) #environ的键值必须是字符串Os.system (' echo $var ')Copy CodeThe code is as follows:Import OSvar=123 or var= ' 1
Recently encountered a requirement, you need to call a function in Python through the shell, it is actually quite simple to find:The Python script is as follows:test.py:ImportConfigparserconfig=Configparser.configparser () config.read ("test.conf")defGet_foo ():returnConfig.get ("Locations","Foo")defGet_bar ():returnConfig.get ("Locations","Bar")I want to invoke
. DEBUG, format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s------->% (Message) s ', Datefmt= '%a,%d%b%Y%h:%m:%s ', filename= '%s/logs/test_timer.log '%location_path, # will log Print to Filemode= ' a ' at the path where the script is located #测试带参数的函数用法, the parameters of the function must be in [] def test_parameters (path): Logging.info ("This is the path of this script:% S "% path" Global Timer timer = Threading. Timer (Test_parameters,[path]) #每60秒运行一次
Sometimes we need a more real-time view of the network card traffic on the server, here I wrote two small script, one with the shell (first, only one network card can be viewed at a time), another in Python (after writing, can view more than one network card).
In the script all use the while true "dead loop", every 10s from "/proc/net/dev" to take a value and calculate 10s within 10s according to the diffe
When writing Python scripts, it is often necessary to invoke system commands, and common Python methods for invoking system commands are mainly Subprocess.call and Os.popen. By default, the Subprocess.call method results in a return value of 1 or 0, while Os.popen is the result of the command run, which can be read with readlines (read all rows, return an array) or read (read all rows, return str).The main
Python read and write to the file is very convenient, and the Linux shell interaction variables need to be converted to use, this is more headache!1 #Coding=utf-82 #!/usr/bin/python3 ImportOS4 Import Time5 #python executes Linux commands6Os.system (': >./aa.py')7 #Human interaction Input8S = Raw_input ("Input:")9os.environ['S']=Str (S)Ten #writes a string s to a
(command)Use the Os.popen () function to execute a command command and return a tuple (Status,output) that represents the return status and execution result of the command execution. The command is executed in the same way as the {command;} 2>1, so the output contains the console outputs or error messages. Output does not contain trailing newline characters.4. Subprocess ModuleThis module was first unveiled in python2.4, which focused on many operations on the process, where call () completely
Recently in a script to try an automatic punch, found a few questions, hereby recorded.Environment:Ubuntu 12.04.4 LTSSelenium 2.43.0Firefox 32.0.31 Originally the machine Selenium,firefox are installed, but Firefox updates from time to time, so selenium may not support the current version of Firefox.Update Selenium command:sudo pip install-u Selenium2 python script used:1 #!/usr/bin/env python2 3 ImportSYS4 fromSeleniumImportWebdriver5 6URL ="http://
Functional Requirements:Simulating the shell's command-line interface with while loops and break implementationsThe source code is as follows:1 ImportOS2 3 whileTrue:##形成死循环 to form a shell environment4cmd = Raw_input ("[email protected] desktop]$")5 ifCmd:##判断是否有输入, there is true, there is no false6 ifcmd = ='Exit':7 Print 'Logout'8 Break9 Else:Ten os.system (cmd) One Else: A Continue ##当输入为空
Using Python to invoke system commands, there are 3 basic options:1. Using the OS module's system methodImport Osos.system ('ls')2. Popen method using the OS moduleImport Osos.popen ('ls')3. Getstatusoutput method using the Commands moduleImport commandscommands.getstatusoutput ('ls')The above 3 ways can call system commands, but in the third way, if the system command error, such as mkdir an existing directory, it will not send out the error message.
stdout can be defined to the file object, tried, can be resolved:
Import subprocess
Import sys
import time
import random
import OS
import re
if __name__ = ' __ Main__ ':
cmdline = []
cmdline.append (' rsync ')
Cmdline.append ('--progress ') cmdline.append ('/kvmdata/kvm/vm_winxp/winxp.img ') cmdline.append ('/root/winxp.img ') Tmpfile = "./tmp/%d.tmp"% random.randint (10000,99999) #临时生成一个文件 fpwrite = open (tmpfile, ' w ') process = Subpro Cess. Popen (cmdline,stdout = Fpwrite,stderr
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.