python脚本的两种调用方式

1、python脚本中经常第一句出现#!/usr/bin/env python或#!/usr/bin/python。这句话的意义下面解释:

脚本语言的第一行,目的就是指出,你想要你的这个文件中的代码用什么可执行程序去运行它,就这么简单

#!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器
#!/usr/bin/env python这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里。当系统看到这一行的时候,首先会到env设置里查找python的安装路径,再调用对应路径下的解释器程序完成操作
#!/usr/bin/python相当于写死了python路径;
#!/usr/bin/env python会去环境设置寻找python目录,推荐这种写法

如果你用 python xxoo.py 来运行,那么写不写都没关系,如果要用 ./xxoo.py 那么就必须加这行, 用来为脚本语言指定解释器.

通常认为用 #!/usr/bin/env python 要比 #!/usr/bin/python 更好,因为 python 解释器有时并不安装在默认路径,例如在 virtualenv 中。

  当你把py文件直接赋予执行权限去执行 ./yourfile.py 的时候,给文件指定一个解释器

而 #!/usr/bin/python 是一般默认的python解释器的路径,所以这种的就是装在默认位置的不会出问题。

但是 #!/usr/bin/envpython 则更加通用一些会去你的PATH 中寻找python 。

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

python脚本的两种调用方式说明:

1、./run.py.shell直接调用python脚本

2、python run.py 调用python 解释器来调用python脚本

 

先分别解释:

1、./run.py调用脚本的方式。shell把run.py当成一般的脚本看待,不把它当成python脚本。按这种方式调用脚本,python 脚本的第一行必须有:

#!/usr/bin/env python3(或#!/usr/bin/env python)

先举例子说明,在说明原因:

未加#!/usr/bin/env python3的情况:

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

a.py:

print ('a')

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

说明:要使用./a.py,必须使用chmoda.py的属性改成可执行的。       

chmod 755 a.py

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

如果a.py是不可执行的,那么./a.py就会报如下错误。

-bash: ./a.py: Permissiondenied

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

在将a.py改为可执行后,如果使用./a.py,还是会报错。

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

./a.py: line 1: `print('a')'

但是,因为我系统中装了python2和python3.

所以,使用#!/usr/bin/env python3提示shell使用python3来调用脚本.

a.py内容如下:---------------------------------------------------------------------------------------------------

#!/usr/bin/env python3

print ('a')

执行结果为:a

 

python3 print函数必须要加上().

所以,如果上述的print('a')变为print 'a',显然是会报错的。

root@iZ28yi4s6zwZ:/mnt/DisplayAdvertisingChallenge/Gbdt_Fm_Kaggle#./a.py

  File "./a.py", line 2

    print 'a'

            ^

SyntaxError: invalidsyntax

以上就说明了,使用./run.py调用python脚本的方式,取决于你在python脚本中第一句,并且使用./run.py必须在脚本文件中写上#!/usr/bin/env python3(或类似的命令),不然都执行不了。

1、先说明一下,我的系统中是预装了python2,然后我装了python3,并且系统默认的python是python2。我装了python3并没有改变系统默认的python解释器,也不建议把系统默认的python解释器改变了,因为像scikit-learn等库很多还是基于python2.7的,你把系统默认的python改成python3会导致很多库出问题。

2、看一下/usr/bin:就知道在ubuntu中,各种软件的安装情况

lrwxrwxrwx 1 root   root         9 Jun 19  2013 python -> python2.7

lrwxrwxrwx 1 root   root         9 Jun 19  2013 python2 -> python2.7

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

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

说明:

1、python-> python2.7:系统默认的python是python2.7

2、python2-> python2.7:python2执行的是python2.7

3、python3-> /opt/python3.3.2/bin/python3.3:python3执行的是/opt/python3.3.2/bin/python3.3

 

现在做个试验:说明使用./run.py的方式,随着第一句#!/usr/bin/envpython3的不同,shell会调用不同的python解释器。

1、

#!/usr/bin/env python3

import subprocess, sys, os, time

NR_THREAD = 1

start = time.time()

cmd = 'converters/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")

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

中断程序查看shell调用哪个python解释器:

File"./run_test.py", line 10, in <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

很明显,使用#!/usr/bin/env python3,那么shell就调用了python3的解释器。

 

2、

 

#!/usr/bin/env python2

import subprocess, sys, os, time

NR_THREAD = 1

start = time.time()

cmd = 'converters/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")

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

中断程序查看shell调用哪个python解释器:

Traceback (most recentcall last):

  File "./run_test.py", line 10, 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

很明显,使用#!/usr/bin/env python2,那么shell就调用了python2的解释器。

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

3、

 

#!/usr/bin/env python

import subprocess, sys, os, time

NR_THREAD = 1

start = time.time()

cmd = 'converters/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")

中断程序查看shell调用哪个python解释器:

  File"./run_test.py", line 10, 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", 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

很明显,使用#!/usr/bin/env python,那么shell就调用了系统默认的python解释器,也就是python2。python -> python2.7。那么,为什么还会出现python3.3.2。那是因为程序中,subprocess.call(cmd, shell=True),开了一个子进程,使用了shell来调用pre-a.py,pre-a.py肯定是使用#!/usr/bin/envpython3

.pre-a.py脚本的内容如下:

#!/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、如果使用python run.py 的方式来调用脚本,那么脚本文件中的第一句#!/usr/bin/envpython3就会被自动略掉,不会起到任何的作用。

python2 run.py代表使用默认的python2解释器来调用脚本。

python3 run.py 代表使用默认的python3解释器来调用脚本。

python run.py 代表使用默认的python解释器来调用脚本。

 

python run_test.py:

^CTraceback (mostrecent call last):

  File "run_test.py", line 10, 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

很明显,python run_test.py,使用默认的python解释器(python2)来调用脚本。

 

python3 run_test.py:

^CTraceback (mostrecent call last):

  File "run_test.py", line 10, 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

很明显,python3 run_test.py,使用python3解释器来调用脚本。

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值