华南俳烁实业有限公司

python

當(dāng)前位置:中華考試網(wǎng) >> python >> python編程基礎(chǔ) >> 文章內(nèi)容

python腳本如何運(yùn)行

來(lái)源:中華考試網(wǎng)  [2020年11月2日]  【

  一、使用python內(nèi)置commands模塊執(zhí)行shell

  commands對(duì)Python的os.popen()進(jìn)行了封裝,使用SHELL命令字符串作為其參數(shù),返回命令的結(jié)果數(shù)據(jù)以及命令執(zhí)行的狀態(tài);

  該命令目前已經(jīng)廢棄,被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模塊執(zhí)行shell

  Python目前已經(jīng)廢棄了os.system,os.spawn*,os.popen*,popen2.*,commands.*來(lái)執(zhí)行其他語(yǔ)言的命令,subprocesss是被推薦的方法;

  subprocess允許你能創(chuàng)建很多子進(jìn)程,創(chuàng)建的時(shí)候能指定子進(jìn)程和子進(jìn)程的輸入、輸出、錯(cuò)誤輸出管道,執(zhí)行后能獲取輸出結(jié)果和執(zhí)行狀態(tài)。

  # 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):

  """執(zhí)行一個(gè)SHELL命令

  封裝了subprocess的Popen方法, 支持超時(shí)判斷,支持讀取stdout和stderr

  參數(shù):

  cwd: 運(yùn)行命令時(shí)更改路徑,如果被設(shè)定,子進(jìn)程會(huì)直接先更改當(dāng)前路徑到cwd

python課程免費(fèi)試聽(tīng)預(yù)約

  • 地區(qū):
  • 姓名:
  • 手機(jī):

  timeout: 超時(shí)時(shí)間,秒,支持小數(shù),精度0.1秒

  shell: 是否通過(guò)shell運(yùn)行

  Returns: return_code

  Raises: Exception: 執(zhí)行超時(shí)

  """

  if shell:

  cmdstring_list = cmdstring

  else:

  cmdstring_list = shlex.split(cmdstring)

  if timeout:

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

  #沒(méi)有指定標(biāo)準(zhǔn)輸出和錯(cuò)誤輸出的管道,因此會(huì)打印到屏幕上;

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

  #subprocess.poll()方法:檢查子進(jìn)程是否結(jié)束了,如果結(jié)束了,設(shè)定并返回碼,放在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為一個(gè)變量,這樣就能直接接收該輸出變量值。

  在python中執(zhí)行SHELL有時(shí)候也是很必須的,比如使用Python的線程機(jī)制啟動(dòng)不同的shell進(jìn)程,目前subprocess是Python官方推薦的方法,其支持的功能也是最多的,推薦大家使用。

  怎么運(yùn)行python腳本

  在Linux中,可以使用nohup將腳本放置后臺(tái)運(yùn)行,如下:

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

  但直接使用上面代碼,無(wú)法在程序運(yùn)行過(guò)程中查看Python中的print "computing" 輸出結(jié)果,比如在每次循環(huán)中使用print語(yǔ)句等。原因是python的輸出有緩沖,導(dǎo)致nohup.out不能夠馬上看到輸出。

  解決方法:

  使用-u參數(shù),使得python不啟用緩沖。

  修改命令如下:

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

  這樣就可以同步看到輸出結(jié)果了。

  運(yùn)行python腳本的方法

  1、直接使用python xxxx.py執(zhí)行。其中python可以寫成python的絕對(duì)路徑。使用which python進(jìn)行查詢。

  2、在文件的頭部(第一行)寫上#!/usr/bin/python2.7,這個(gè)地方使用python的絕對(duì)路徑,就是上面用which python查詢來(lái)的結(jié)果。

  再用chmod改變文件的執(zhí)行權(quán)限,然后在外面就可以使用./xxx.py或xxx.py執(zhí)行了。

  因?yàn)樵趌inux中,python啊shell這些程序都是普通的文本格式,都需要一種程序去解釋執(zhí)行它。要么調(diào)用的時(shí)候指定,要么在文件頭指定。

  python腳本直接執(zhí)行的方式

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

  2. 另外還有一種寫法是#! /usr/bin/env python編輯完成python腳本文件后為它加上可執(zhí)行權(quán)限。例如你的python腳本文件叫做runit.py,那么就在shell中輸入如下命令:chmod +x runit.py

  之后直接在shell中輸入./runit.py就可以執(zhí)行你的python程序了。當(dāng)然這是在Linux下的操作

  3. 如果想在windows下直接執(zhí)行Python程序,就需要使用py2exe工具將python源程序編譯成exe文件了。

責(zé)編:fushihao
  • 會(huì)計(jì)考試
  • 建筑工程
  • 職業(yè)資格
  • 醫(yī)藥考試
  • 外語(yǔ)考試
  • 學(xué)歷考試
马龙县| 教育| 承德县| 夏河县| 双峰县| 道真| 枣阳市| 沅陵县| 永仁县| 大埔县| 仙居县| 夏津县| 塔河县| 布尔津县| 凯里市| 敦化市| 千阳县| 辰溪县| 富川| 界首市| 乐亭县| 黄石市| 博乐市| 盈江县| 吉木乃县| 晋中市| 商都县| 鄂伦春自治旗| 惠州市| 夏河县| 常山县| 林州市| 泌阳县| 陇川县| 达日县| 阳谷县| 兰西县| 丰都县| 罗源县| 尼木县| 临西县|