python

当前位置:中华考试网 >> python >> python编程基础 >> 文章内容

python脚本如何运行

来源:中华考试网  [2020年11月2日]  【

  一、使用python内置commands模块执行shell

  commands对Python的os.popen()进行了封装,使用SHELL命令字符串作为其参数,返回命令的结果数据以及命令执行的状态;

  该命令目前已经废弃,被subprocess所替代;

  # coding=utf-8

  '''

  Created on 2013年11月22日

  @author: crazyant.net

  '''

  import commands

  import pprint

  def cmd_exe(cmd_String):

  print "will exe cmd,cmd:"+cmd_String

  return commands.getstatusoutput(cmd_String)

  if __name__=="__main__":

  pprint.pprint(cmd_exe("ls -la"))

  二、使用python最新的subprocess模块执行shell

  Python目前已经废弃了os.system,os.spawn*,os.popen*,popen2.*,commands.*来执行其他语言的命令,subprocesss是被推荐的方法;

  subprocess允许你能创建很多子进程,创建的时候能指定子进程和子进程的输入、输出、错误输出管道,执行后能获取输出结果和执行状态。

  # coding=utf-8

  '''

  Created on 2013年11月22日

  @author: crazyant.net

  '''

  import shlex

  import datetime

  import subprocess

  import time

  def execute_command(cmdstring, cwd=None, timeout=None, shell=False):

  """执行一个SHELL命令

  封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr

  参数:

  cwd: 运行命令时更改路径,如果被设定,子进程会直接先更改当前路径到cwd

  timeout: 超时时间,秒,支持小数,精度0.1秒

  shell: 是否通过shell运行

  Returns: return_code

  Raises: Exception: 执行超时

  """

  if shell:

  cmdstring_list = cmdstring

  else:

  cmdstring_list = shlex.split(cmdstring)

  if timeout:

  end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)

  #没有指定标准输出和错误输出的管道,因此会打印到屏幕上;

  sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)

  #subprocess.poll()方法:检查子进程是否结束了,如果结束了,设定并返回码,放在subprocess.returncode变量中

  while sub.poll() is None:

  time.sleep(0.1)

  if timeout:

  if end_time <= datetime.datetime.now():

  raise Exception("Timeout:%s"%cmdstring)

  return str(sub.returncode)

  if __name__=="__main__":

  print execute_command("ls")

  也可以在Popen中指定stdin和stdout为一个变量,这样就能直接接收该输出变量值。

  在python中执行SHELL有时候也是很必须的,比如使用Python的线程机制启动不同的shell进程,目前subprocess是Python官方推荐的方法,其支持的功能也是最多的,推荐大家使用。

  怎么运行python脚本

  在Linux中,可以使用nohup将脚本放置后台运行,如下:

  nohup python myscript.py params1 > nohup.out 2>&1 &

  但直接使用上面代码,无法在程序运行过程中查看Python中的print "computing" 输出结果,比如在每次循环中使用print语句等。原因是python的输出有缓冲,导致nohup.out不能够马上看到输出。

  解决方法:

  使用-u参数,使得python不启用缓冲。

  修改命令如下:

  nohup python -u myscript.py params1 > nohup.out 2>&1 &

  这样就可以同步看到输出结果了。

  运行python脚本的方法

  1、直接使用python xxxx.py执行。其中python可以写成python的绝对路径。使用which python进行查询。

  2、在文件的头部(第一行)写上#!/usr/bin/python2.7,这个地方使用python的绝对路径,就是上面用which python查询来的结果。

  再用chmod改变文件的执行权限,然后在外面就可以使用./xxx.py或xxx.py执行了。

  因为在linux中,python啊shell这些程序都是普通的文本格式,都需要一种程序去解释执行它。要么调用的时候指定,要么在文件头指定。

  python脚本直接执行的方式

  1. 在python文件里第一行加上#! /usr/bin/python,即你的python解释器所在的目录。

  2. 另外还有一种写法是#! /usr/bin/env python编辑完成python脚本文件后为它加上可执行权限。例如你的python脚本文件叫做runit.py,那么就在shell中输入如下命令:chmod +x runit.py

  之后直接在shell中输入./runit.py就可以执行你的python程序了。当然这是在Linux下的操作

  3. 如果想在windows下直接执行Python程序,就需要使用py2exe工具将python源程序编译成exe文件了。

责编:fushihao
  • 会计考试
  • 建筑工程
  • 职业资格
  • 医药考试
  • 外语考试
  • 学历考试