Let's say we have a task: simply test whether a computer in a local area network is connected. The IP range of these computers ranges from 192.168.0.101 to 192.168.0.200.
Idea: Programming with the shell. (Linux is usually bash and Windows is a batch script). For example, use the ping IP command on Windows to test each machine sequentially and get console output. The console text is usually "Reply from ..." Because of the ping pass. "When the text is" Time out ... , so the string lookup in the results will tell if the machine is connected.
Implementation: Java code is as follows:
String cmd= "cmd.exe ping"; String ipprefix= "192.168.10."; int Begin=101;int end=200; Process p=null;for (int i=begin;i<end;i++) { p= runtime.getruntime (). exec (cmd+i); String line = null; BufferedReader reader = new BufferedReader (New InputStreamReader (P.getinputstream ())); while (line = Reader.readline ())! = null) { //handling line, may logs it. } Reader.close (); P.destroy ();}
This code works well, and the problem is that you need to do some extra work to run the code. These additional tasks include:
- Write a class file
- Write a Main method
- Compile it into a byte code
- Since the byte code cannot be run directly, you need to write a little bat or bash script to run it.
Of course, the same work can be done in C + +. But C + + is not a cross-platform language. In this simple enough example, it may not be possible to see the difference between C + + and Java implementations, but in some more complex scenarios, For example, to record connectivity or not information to the network database. Because Linux and Windows have different network interfaces, you have to write two versions of the function. There is no such concern with Java.
The same work is done with Python as follows:
Import subprocesscmd= "cmd.exe" Begin=101end=200while begin<end: p=subprocess. Popen (cmd,shell=true,stdout=subprocess. PIPE, stdin=subprocess. PIPE, stderr=subprocess. PIPE) p.stdin.write ("Ping 192.168.1.") +STR (BEGIN) + "\ n") p.stdin.close () p.wait () print "Execution result:%s"%p.stdout.read ()
Comparing Java,python is more concise and you write faster. You do not need to write the main function, and this program can be run directly after saving. In addition, like Java, Python is also cross-platform.
Experienced C/java programmers may argue that writing with C/java is faster than Python. This view is a matter of opinion. My idea is that when you master Java and Python at the same time, You will find that writing this kind of program in Python is much faster than Java. For example, you only need one line of code to manipulate a local file, and you don't need a lot of Java's streaming wrapper classes. Various languages have their natural suitable application range. Using Python to process some short programs like interacting with the operating system is the most time-saving task. .
Simple enough tasks, such as some shell programming. If you prefer to use Python to design large commercial websites or design complex games, you're on your own.
2 Quick Start
After you install Python (my version of this machine is 2.5.4), open the idle (Python GUI), which is the Python language interpreter, and the statements you write can be run immediately. Let's write down a famous program sentence:
Print "hello,world!"
and press ENTER. You can see this quote that was introduced into the world of programming by K&r.
In the Interpreter, select "File"--"New Window" or shortcut CTRL + N to open a new editor. Write down the following statement:
Print "hello,world!" Raw_input ("Press ENTER key to close this window");
Save as a.py file. Press F5, and you can see the results of the program running. This is the second way to run Python.
Locate the a.py file you saved, and double-click it. You can also see the program results. Python programs can run directly, compared to Java, which is an advantage.
We will greet the world in a different way. Create a new editor and write the following code:
Print "Welcome to Olympic China!" Raw_input ("Press ENTER key to close this window");
When you save the code, Python will prompt you to change the character set of the file, as follows:
#-*-coding:cp936-*-print "Welcome to Olympic China!" Raw_input ("Press ENTER key to close this window");
Change the character set to the form we are more familiar with:
#-*-CODING:GBK-*-print "Welcome to Olympic China!" # Use the example of Chinese raw_input ("press ENTER key to close this window");
The program works as well.
It's too much trouble to count the calculators that came with Microsoft. Open the Python interpreter and calculate directly:
A=100.0b=201.1c=2343print (a+b+c)/C
You can print a string of predefined output formats as follows:
Print "" "usage:thingy [OPTIONS]- h Display This Usage message- h hostname hostname to connect to" ""
How is the string accessed? See this example:
Word= "ABCDEFG" A=word[2]print "A is:" +ab=word[1:3]print "B was:" +b # index 1 and 2 elements of Word.c=word[:2]print "C is: "+c # Index 0 and 1 elements of Word.d=word[0:]print" D is: "+d # all elements of Word.e=word[:2]+word[2:]print" E is: "+ E # all elements of Word.f=word[-1]print ' F is: ' +f # The last elements of Word.g=word[-4:-2]print ' G is: ' +g # index 3 an D 4 Elements of Word.h=word[-2:]print "H is:" +h # The last of the Elements.i=word[:-2]print "I Was:" +i # everything except T He last the Charactersl=len (word) print "Length of Word is:" + str (l)
Note the differences between ASCII and Unicode strings:
Print "Input Your Chinese Name:" S=raw_input ("press ENTER to being continued");p rint "Your name is :" +s;l=len (s) print "L Ength of your Chinese name in ASC codes are: "+str (L); A=unicode (S," GBK ") L=len (a) print" I ' m sorry we should use Unicode char! Characters number of your Chinese name in Unicode is: "+str (L);
Like a list in Java, this is an easy-to-use data type:
Word=[' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G ']a=word[2]print ' A is: ' +ab=word[1:3]print ' B is: ' Print B # index 1 and 2 elements of Wo Rd.c=word[:2]print "C is:" Print C # index 0 and 1 elements of Word.d=word[0:]print "D are:" Print D # all elements of Word . E=word[:2]+word[2:]print ' E is: ' Print e # all elements of Word.f=word[-1]print ' F is: ' Print F # The last elements of Wo Rd.g=word[-4:-2]print "G is:" Print G # index 3 and 4 elements of Word.h=word[-2:]print "H are:" Print H # The last of the Ele Ments.i=word[:-2]print "I am:" Print I # everything except the last of the Charactersl=len (word) print "Length of Word is:" + STR (l) print "Adds new element" Word.append (' h ') print word
# Multi-way Decisionx=int (raw_input ("Please enter a integer:")) if x<0: x=0 print "negative changed to zero" Elif x==0: print "Zero" Else: print "More" # Loops Lista = [' Cat ', ' windows ', ' Defenestrate ']for x in a: print x, Len (x)
# Define and Invoke Function.def sum (A, B): return a+bfunc = SUMR = Func (5,6) print r# defines function with default arg Umentdef Add (a,b=2): return A+br=add (1) Print rr=add (1,5) print R
Also, a handy function is introduced:
# The range () Functiona =range (5,10) Print AA = Range ( -2,-7) Print AA = Range ( -7,-2) Print AA = Range ( -2,-11,-3) # the 3rd PA Rameter stands for Stepprint A
Spath= "D:/download/baa.txt" F=open (spath, "W") # Opens file for writing. Creates this file doesn ' t exist.f.write ("first line 1.\n") f.writelines ("First line 2.") F.close () F=open (spath, "R") # Opens file for readingfor line in F: print linef.close ()
S=raw_input ("Input your Age:") if s = = "": Raise Exception ("Input must no be empty.") Try: I=int (s) except ValueError: print "Could not convert data to an integer." Except: print "Unknown exception!" Else: # It is useful for code this must be executed if the TRY clause does not raise a exception print "You are%d"% I, "years old" finally: # Clean up action print "goodbye!"
Class Base: def __init__ (self): self.data = [] def add (self, x): self.data.append (x) def addtwice (Self, x): self.add (x) Self.add (x) # Child extends BaseClass child (Base): def Plus (self,a,b): return a +bochild =child () ochild.add ("str1") print Ochild.dataprint ochild.plus (2,3)
Each of the. py files is called a module,module that can be imported between each other. See the following example: # A.pydef Add_func (A, B): return a+b
# B.pyfrom A import add_func # Also can be:import aprint "import add_func from Module a" print "Result of 1 plus 2 are:" P Rint add_func # If using "Import a", then here should be "A.add_func"
Module can be defined inside the package. Python defines the package in a slightly odd way, assuming that we have a parent folder that has a child subfolder. There is a module a.py. How do I get Python to know this file hierarchy? It's easy to put a file named _init_.py in each directory. The contents of the file can be empty. The hierarchy is as follows:
Parent --__init_.py --child --__init_.py --a.pyb.py
So how does python find the module we define? In standard package SYS, the Path property records the Python package path. You can print it out:
Import Sysprint Sys.path
Usually we can put the module's package path into the environment variable Pythonpath, which is automatically added to the Sys.path property. Another convenient way is to directly specify our module path to Sys.path in programming:
Import syssys.path.append (' D:\\download ') from parent.child.a import add_funcprint sys.pathprint "Import Add_func from Module A "print" Result of 1 plus 2 is: "Print Add_func
Summarize
You will find this tutorial quite simple. Many of the python features are implicitly presented in the code, including: Python does not need to explicitly declare data types, keyword descriptions, the interpretation of string functions, and so on. I think a skilled programmer should understand these concepts quite well, So after you squeeze out the precious hour to read this short tutorial, you'll be able to familiarize yourself with Python as soon as possible with the knowledge of the migration analogy, and then start programming with it as soon as possible.
Of course, the 1-hour learning of Python is quite grandstanding. Specifically, the programming language includes syntax and standard libraries. Grammar is equivalent to martial arts, while standard library application practice is similar to internal strength, requiring long-term exercise. Python learns Java's strengths and provides a number of easy-to-use standard libraries for programmers to "take doctrine". (This is also why Python succeeds), and at the beginning we see examples of how Python invokes Windows cmd, and I'll try to write about the usage of the standard libraries and some application techniques in the future so that you can really master Python.
Python Getting Started tutorial super detailed 1 hours learn python