検索

python相似模块用例

Jun 10, 2016 pm 03:05 PM
pythonthreadモジュール

一:threading VS Thread

众所周知,python是支持多线程的,而且是native的线程,其中threading是对Thread模块做了包装,可以更加方面的被使用,threading模块里面主要对一些线程操作对象化了,创建了Thread的类。

使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行,一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的类里面,用例如下:

①使用Thread来实现多线程

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import string
import threading 
import time

def threadMain(a):
  global count,mutex
  #获得线程名
  threadname = threading.currentThread().getName()

  for x in xrange(0,int(a)):
    #获得锁
    mutex.acquire()
    count += 1
    #释放锁
    mutex.release()
    print threadname,x,count
    time.sleep()

def main(num):
  global count,mutex
  threads = []
  count = 1
  #创建一个锁
  mutex = threading.Lock()
  #先创建线程对象
  for x in xrange(0,num):
    threads.append(threading.Thread(target = threadMain,args=(10,)))
  for t in threads:
    t.start()
  for t in threads:
    t.join()

if __name__ == "__main__":
  num = 4
  main(num);

②使用threading来实现多线程

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import threading
import time

class Test(threading.Thread):
  def __init__(self,num):
    threading.Thread.__init__(self):
    self._run_num = num

  def run(self):
    global count,mutex
    threadName = threading.currentThread.getName()
    for x in xrange(0,int(self._run_num)):
      mutex.acquire()
      count += 1
      mutex.release()
      print threadName,x,count
      time.sleep(1)

if __name__ == "__main__":
  global count,mutex
  threads = []
  num = 4
  count = 1
  mutex.threading.Lock()
  for x in xrange(o,num):
    threads.append(Test(10))
  #启动线程
  for t in threads:
    t.start()
  #等待子线程结束
  for t in threads:
    t.join()

二:optparser VS getopt

①使用getopt模块处理Unix模式的命令行选项

getopt模块用于抽出命令行选项和参数,也就是sys.argv,命令行选项使得程序的参数更加灵活,支持短选项模式和长选项模式

例:python scriptname.py –f “hello” –directory-prefix=”/home” –t  --format ‘a'‘b'

getopt函数的格式:getopt.getopt([命令行参数列表],‘短选项',[长选项列表])

其中短选项名后面的带冒号(:)表示该选项必须有附加的参数

长选项名后面有等号(=)表示该选项必须有附加的参数

返回options以及args

options是一个参数选项及其value的元组((‘-f','hello'),(‘-t',''),(‘—format',''),(‘—directory-prefix','/home'))

args是除去有用参数外其他的命令行 输入(‘a',‘b')

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
import getopt

def Usage():
  print "Usage: %s [-a|-0|-c] [--help|--output] args..."%sys.argv[0]

if __name__ == "__main__":
  try:
    options,args = getopt.getopt(sys.argv[1:],"ao:c",['help',"putput="]):
    print options
    print "\n"
    print args

    for option,arg in options:
      if option in ("-h","--help"):
        Usage()
        sys.exit(1)
      elif option in ('-t','--test'):
        print "for test option"
      else:
        print option,arg
  except getopt.GetoptError:
    print "Getopt Error"
    Usage()
    sys.exit(1)

②optparser模块

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import optparser
def main():
  usage = "Usage: %prog [option] arg1,arg2..."
  parser = OptionParser(usage=usage)
  parser.add_option("-v","--verbose",action="store_true",dest="verbose",default=True,help="make lots of noise [default]")
  parser.add_option("-q","--quiet",action="store_false",dest="verbose",help="be vewwy quiet (I'm hunting wabbits)")
  parser.add_option("-f","--filename",metavar="FILE",help="write output to FILE")
  parser.add_option("-m","--mode",default="intermediate",help="interaction mode: novice, intermediate,or expert [default: %default]")
  (options,args) = parser.parse_args()
  if len(args) != 1:
    parser.error("incorrect number of arguments")
  if options.verbose:
    print "reading %s..." %options.filename 

if __name__ == "__main__":
  main()

以上就是threading VS Thread、optparser VS getopt 的相互比较,希望对大家学习模块有所帮助。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonアレイで実行できる一般的な操作は何ですか?Pythonアレイで実行できる一般的な操作は何ですか?Apr 26, 2025 am 12:22 AM

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

一般的に使用されているnumpy配列はどのようなアプリケーションにありますか?一般的に使用されているnumpy配列はどのようなアプリケーションにありますか?Apr 26, 2025 am 12:13 AM

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

Pythonのリスト上の配列を使用するのはいつですか?Pythonのリスト上の配列を使用するのはいつですか?Apr 26, 2025 am 12:12 AM

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

すべてのリスト操作は配列でサポートされていますか?なぜまたはなぜですか?すべてのリスト操作は配列でサポートされていますか?なぜまたはなぜですか?Apr 26, 2025 am 12:05 AM

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト

Pythonリストの要素にどのようにアクセスしますか?Pythonリストの要素にどのようにアクセスしますか?Apr 26, 2025 am 12:03 AM

toaccesselementsinapythonlist、useindexing、negativeindexing、slicing、oriteration.1)indexingstartsat0.2)negativeindexingAcsesess.3)slicingextractStions.4)reterationSuseSuseSuseSuseSeSeS forLoopseCheckLentlentlentlentlentlentlenttodExeror。

Pythonを使用した科学コンピューティングでアレイはどのように使用されていますか?Pythonを使用した科学コンピューティングでアレイはどのように使用されていますか?Apr 25, 2025 am 12:28 AM

Arraysinpython、特にvianumpy、arecrucialinscientificComputing fortheirefficienty andversitility.1)彼らは、fornumericaloperations、data analysis、andmachinelearning.2)numpy'simplementation incensuresfasteroperationsthanpasteroperations.3)arayableminablecickick

同じシステムで異なるPythonバージョンをどのように処理しますか?同じシステムで異なるPythonバージョンをどのように処理しますか?Apr 25, 2025 am 12:24 AM

Pyenv、Venv、およびAnacondaを使用して、さまざまなPythonバージョンを管理できます。 1)Pyenvを使用して、複数のPythonバージョンを管理します。Pyenvをインストールし、グローバルバージョンとローカルバージョンを設定します。 2)VENVを使用して仮想環境を作成して、プロジェクトの依存関係を分離します。 3)Anacondaを使用して、データサイエンスプロジェクトでPythonバージョンを管理します。 4)システムレベルのタスク用にシステムPythonを保持します。これらのツールと戦略を通じて、Pythonのさまざまなバージョンを効果的に管理して、プロジェクトのスムーズな実行を確保できます。

標準のPythonアレイでnumpyアレイを使用することの利点は何ですか?標準のPythonアレイでnumpyアレイを使用することの利点は何ですか?Apr 25, 2025 am 12:21 AM

numpyarrayshaveveraladvantages-averstandardpythonarrays:1)thealmuchfasterduetocベースのインプレンテーション、2)アレモレメモリ効率、特にlargedatasets、および3)それらは、拡散化された、構造化された形成術科療法、

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール