Two ways to invoke Python scripts __python

Source: Internet
Author: User
Tags chmod python script

1, Python scripts often appear in the first sentence #!/usr/bin/env python or #!/usr/bin/python. The meaning of this sentence is explained below:

The first line of the scripting language is to point out that you want the code in your file to run it with what executable program, and that's simple.

#!/usr/bin/python is to tell the operating system to execute this script, call the Python interpreter under/usr/bin;
The use of #!/usr/bin/env Python is designed to prevent operating system users from not having Python installed in the default/usr/bin path. When the system sees this line, it first looks in the env settings to find the Python installation path, and then calls the interpreter program in the corresponding path to complete the operation.
#!/usr/bin/python is equivalent to writing dead python path;
#!/usr/bin/env Python will go to the environment settings to find the Python directory, recommend this writing

If you run it with Python xxoo.py, it doesn't matter if you write it, if you want to use./xxoo.py then you have to add this line to specify the interpreter for the scripting language.

It is generally considered better to use #!/usr/bin/env python than #!/usr/bin/python because the Python interpreter is sometimes not installed in the default path, such as in Virtualenv.

Specify an interpreter for the file when you assign the py file directly to the Execute permission to execute./yourfile.py.

The #!/usr/bin/python is the path to the general default Python interpreter, so this is not a problem with the default location.

But #!/usr/bin/envpython is more general. Some will look for Python in your path.

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------

Two ways to invoke Python scripts are described:

1./run.py.shell call Python script directly

2, Python run.py invoke the Python interpreter to invoke the Python script

First explain separately:

1./run.py the way to invoke the script. The shell treats run.py as a generic script, not as a Python script. To invoke the script in this way, the first line of the Python script must be:

#!/usr/bin/env Python3 (or #!/usr/bin/env python)

Let me give you an example to illustrate why:

Without #!/usr/bin/env Python3:

--------------------------------------------------------------------------------------------------------------- -------

a.py:

Print (' a ')

--------------------------------------------------------------------------------------------------------------- -------

Note: to use./a.py, you must use chmod to change the a.py properties to executable.

chmod 755 a.py

-rwxr-xr-x 1 root Nov 09:43 a.py

If the a.py is not enforceable, then/a.py will report the following error.

-bash:./a.py:permissiondenied

--------------------------------------------------------------------------------------------------------------- -------

When you change a.py to executable, if you use./a.py, you will still get an error.

./a.py:line 1:syntaxerror near unexpected token ' a '

./a.py:line 1: ' Print (' a ') '

However, because my system loaded with Python2 and Python3.

So, use the #!/usr/bin/env Python3 prompt Shell to invoke the script using Python3.

The contents of the a.py are as follows:---------------------------------------------------------------------------------------------------

#!/usr/bin/env Python3

Print (' a ')

Execution Result: a

The Python3 print function must be added ().

So, if the above print (' a ') changes to print ' a ', it will obviously be an error.

root@iz28yi4s6zwz:/mnt/displayadvertisingchallenge/gbdt_fm_kaggle#./a.py

File "./a.py", line 2

print ' A '

^

Syntaxerror:invalidsyntax

As you can tell, using./run.py to invoke Python scripts depends on the first sentence in your Python script, and you use the./run.py must write the #!/usr/bin/env python3 (or similar command) in the script file, otherwise it will not execute.

1, first of all, my system is pre-installed python2, and then I installed the Python3, and the system default Python is Python2. I installed Python3 did not change the system default Python interpreter, nor did it recommend that the system default Python interpreter be changed, Because many libraries, such as Scikit-learn, are based on python2.7, you change the system default Python to Python3, which can cause a lot of library problems.

2, look at/usr/bin: You know in Ubuntu, the installation of various software

lrwxrwxrwx 1 Root 9 June 2013 Python-> python2.7

lrwxrwxrwx 1 Root 9 June 2013 Python2-> python2.7

-rwxr-xr-x 1 root root 2985296 Dec 2014 python2.7

lrwxrwxrwx 1 root Nov 10:08 python3->/opt/python3.3.2/bin/python3.3

Description

1, python-> python2.7: The system default Python is python2.7

2, python2-> python2.7:python2 execution is python2.7

3, python3->/opt/python3.3.2/bin/python3.3:python3 execution is/opt/python3.3.2/bin/python3.3

Now do a trial: explain how to use./run.py, the shell will invoke a different Python interpreter as the first sentence #!/usr/bin/envpython3.

1,

#!/usr/bin/env python3

Import subprocess, sys, OS, time

nr_thread = 1

start = Time.time ()

cmd = ' Converte rs/pre-a.py trainsample0.25.csv tr.gbdt.dense tr.gbdt.sparse '
subprocess.call (cmd, shell=true)

cmd = ' converters/pre-a.py testsample0.25.csv te.gbdt.dense te.gbdt.sparse '
subprocess.call (cmd, shell=true)

Print ("End pre-a.py")

--------------------------------------------------------------------------------------------------------------- -------

Interrupt program to see which Python interpreter the shell calls:

File "./run_test.py", line, <module>

Subprocess.call (cmd, shell=true)

File "/opt/python3.3.2/lib/python3.3/subprocess.py", line 522, Incall

Traceback (most recentcall last):

File "converters/pre-a.py", Line36, in <module>

Key = Field + '-' + Row[field]

Keyboardinterrupt

Return p.wait (Timeout=timeout)

File "/opt/python3.3.2/lib/python3.3/subprocess.py", line 1528,in wait

(PID, STS) = self._try_wait (0)

File "/opt/python3.3.2/lib/python3.3/subprocess.py", line 1485,in _try_wait

(PID, STS) = _eintr_retry_call (Os.waitpid,self.pid, Wait_flags)

File "/opt/python3.3.2/lib/python3.3/subprocess.py", line 476, In_eintr_retry_call

return func (*args)

Keyboardinterrupt

Obviously, using the #!/usr/bin/env Python3, the shell invokes the Python3 interpreter.

2,

#!/usr/bin/env python2

Import subprocess, sys, OS, time

nr_thread = 1

start = Time.time ()

cmd = ' Converte rs/pre-a.py trainsample0.25.csv tr.gbdt.dense tr.gbdt.sparse '
subprocess.call (cmd, shell=true)

cmd = ' converters/pre-a.py testsample0.25.csv te.gbdt.dense te.gbdt.sparse '
subprocess.call (cmd, shell=true)

Print ("End pre-a.py")

--------------------------------------------------------------------------------------------------------------- -------

Interrupt program to see which Python interpreter the shell calls:

Traceback (most recentcall last):

File "./run_test.py", line, in<module>

Subprocess.call (cmd, shell=true)

File "/usr/lib/python2.7/subprocess.py", line 493, in call

Return Popen (*popenargs, **kwargs). Wait ()

File "/usr/lib/python2.7/subprocess.py", line 1291, in wait

PID, sts = _eintr_retry_call (os.waitpid,self.pid, 0)

File "/usr/lib/python2.7/subprocess.py", line 478, in _eintr_retry_call

return func (*args)

Keyboardinterrupt

Obviously, using the #!/usr/bin/env Python2, the shell invokes the Python2 interpreter.

--------------------------------------------------------------------------------------------------------------- -------

3,

#!/usr/bin/env python

import subprocess, sys, OS, time

nr_thread = 1

start = Time.time ()

cmd = ' converter s/pre-a.py trainsample0.25.csv tr.gbdt.dense tr.gbdt.sparse '
subprocess.call (cmd, shell=true)

cmd = ' converters/pre-a.py testsample0.25.csv te.gbdt.dense te.gbdt.sparse '
subprocess.call (cmd, shell=true)

Print ("endpre-a.py")

Interrupt program to see which Python interpreter the shell calls:

File "./run_test.py", line, <module>

Subprocess.call (cmd, shell=true)

File "/usr/lib/python2.7/subprocess.py", line 493, in call

Return Popen (*popenargs, **kwargs). Wait ()

File "/usr/lib/python2.7/subprocess.py", line 1291, in wait

PID, sts = _eintr_retry_call (os.waitpid,self.pid, 0)

File "/usr/lib/python2.7/subprocess.py", line 478, in _eintr_retry_call

return func (*args)

Keyboardinterrupt

Root@iz28yi4s6zwz:/mnt/displayadvertisingchallenge/gbdt_fm_kaggle#traceback (most recent call last):

File "converters/pre-a.py", Line19, in <module>

For row incsv. Dictreader (Open (args[' Csv_path ')):

File "/opt/python3.3.2/lib/python3.3/csv.py", line 118, in__next__

D = dict (Zip (self.fieldnames, row))

Keyboardinterrupt

Obviously, using #!/usr/bin/env python, the shell invokes the system's default Python interpreter, which is python2. Python-> python2.7. Why, then, will there be python3.3.2. That is because the program, Subprocess.call (CMD, shell=true), opened a subprocess, using the shell to invoke the pre-a.py,pre-a.py is definitely using #!/usr/bin/envpython3

The contents of the. pre-a.py script are as follows:

#!/usr/bin/env python3

Import argparse, CSV, sys from

common import *

if Len (sys.argv) = = 1:
    Sys.argv.append ('-h ')

parser = Argparse. Argumentparser ()
parser.add_argument (' Csv_path ', type=str)
parser.add_argument (' Dense_path ', type=str)
parser.add_argument (' Sparse_path ', type=str)
args = VARs (Parser.parse_args ())

--------------------------------------------------------------------------------------------------------------- -------

2. If you use Python run.py to invoke the script, the first sentence in the script file will be #!/usr/bin/envpython3 automatically and will not work.

The Python2 run.py represents the use of the default Python2 interpreter to invoke the script.

The Python3 run.py represents the use of the default Python3 interpreter to invoke the script.

The Python run.py represents using the default Python interpreter to invoke the script.

Python run_test.py:

^ctraceback (Mostrecent call last):

File "run_test.py", line, in<module>

Subprocess.call (cmd, shell=true)

File "/usr/lib/python2.7/subprocess.py", line 493, in call

Return Popen (*popenargs, **kwargs). Wait ()

File "/usr/lib/python2.7/subprocess.py", line 1291, in wait

PID, sts = _eintr_retry_call (os.waitpid,self.pid, 0)

File "/usr/lib/python2.7/subprocess.py", line 478, in _eintr_retry_call

return func (*args)

Keyboardinterrupt

Root@iz28yi4s6zwz:/mnt/displayadvertisingchallenge/gbdt_fm_kaggle#traceback (most recent call last):

File "converters/pre-a.py", Line22, in <module>

val = row[' i{0} '. Format (j)]

Keyboardinterrupt

Obviously, Python run_test.py uses the default Python interpreter (Python2) to invoke the script.

Python3 run_test.py:

^ctraceback (Mostrecent call last):

File "run_test.py", line, in<module>

Subprocess.call (cmd, shell=true)

File "/opt/python3.3.2/lib/python3.3/subprocess.py", line 522, in call

Return p.wait (Timeout=timeout)

File "/opt/python3.3.2/lib/python3.3/subprocess.py", line 1528, in wait

(PID, STS) = self._try_wait (0)

File "/opt/python3.3.2/lib/python3.3/subprocess.py", line 1485, in _try_wait

(PID, STS) = _eintr_retry_call (Os.waitpid,self.pid, Wait_flags)

File "/opt/python3.3.2/lib/python3.3/subprocess.py", line 476, in _eintr_retry_call

return func (*args)

Keyboardinterrupt

Root@iz28yi4s6zwz:/mnt/displayadvertisingchallenge/gbdt_fm_kaggle#traceback (most recent call last):

File "converters/pre-a.py", Line19, in <module>

For row incsv. Dictreader (Open (args[' Csv_path ')):

File "/opt/python3.3.2/lib/python3.3/csv.py", line 118, in __next__

D = dict (Zip (self.fieldnames, row))

Keyboardinterrupt

Obviously, Python3 run_test.py, use the PYTHON3 interpreter to invoke the script.

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.