导航:首页 > 编程语言 > python脚本代码片段

python脚本代码片段

发布时间:2022-06-20 06:27:17

Ⅰ 求简洁优美的python代码例子、片段、参考资料

楼主贴的那段代码好像是我写的那段吧,我来告诉你如何写出来的吧

首先我不是高手,我也没有人教,我的编程都是自学的,我只是一个业余爱好者.

写出这样的代码很简单,就是要多练,我只是把python的基本语法学会,然后就不停地练习,我没有看过楼上的那些资料,我只是不停地码代码,或许有捷径,但是我没有发现.

我从07年开始写python的脚本,我一开始的代码风格也很差,特别是我先学c++,然后再转python的,当写的代码越来越多,对python的了解就会加深,代码风格也会自动改变的,不需要着急,其实这就是对一门语言的了解程度,你可以看看我回答的问题,我的回答就是我对python的理解,如果你能坚持下来,相信7年后你写的代码会比我写得更好.



楼上的题目有点意思,我也写一下,不知道对否

s='''
TheZenofPython,byTimPeters

Beautifulisbetterthanugly.
Explicitisbetterthanimplicit.
Simpleisbetterthancomplex.
.
Flatisbetterthannested.
Sparseisbetterthandense.
Readabilitycounts.
Specialcasesaren'tspecialenoughtobreaktherules.
.
Errorsshouldneverpasssilently.
Unlessexplicitlysilenced.
Inthefaceofambiguity,refusethetemptationtoguess.
Thereshouldbeone--andpreferablyonlyone--obviouswaytodoit.
'reDutch.
Nowisbetterthannever.
*right*now.
,it'sabadidea.
,itmaybeagoodidea.
--let'sdomoreofthose!
'''

importre,collections
tail_map={"'s":'is',"'re":'are',"n't":'not'}
data=collections.Counter(re.findall('w+',re.sub("('s|'re|n't)",lambdamatchobj:tail_map[matchobj.group()],s.lower())))

max_len=max(data.values())
print('Totalwordcount:%d',sum(data.values()))

forwordinsorted(data):
print('%*s=>%d'%(max_len,word,data[word]))

Ⅱ 如何使用python编写测试脚本

1)doctest
使用doctest是一种类似于命令行尝试的方式,用法很简单,如下

复制代码代码如下:

def f(n):
"""
>>> f(1)
1
>>> f(2)
2
"""
print(n)

if __name__ == '__main__':
import doctest
doctest.testmod()

应该来说是足够简单了,另外还有一种方式doctest.testfile(filename),就是把命令行的方式放在文件里进行测试。

2)unittest
unittest历史悠久,最早可以追溯到上世纪七八十年代了,C++,Java里也都有类似的实现,Python里的实现很简单。
unittest在python里主要的实现方式是TestCase,TestSuite。用法还是例子起步。

复制代码代码如下:

from widget import Widget
import unittest
# 执行测试的类
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget()
def tearDown(self):
self.widget.dispose()
self.widget = None
def testSize(self):
self.assertEqual(self.widget.getSize(), (40, 40))
def testResize(self):
self.widget.resize(100, 100)
self.assertEqual(self.widget.getSize(), (100, 100))
# 测试
if __name__ == "__main__":
# 构造测试集
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase("testSize"))
suite.addTest(WidgetTestCase("testResize"))

# 执行测试
runner = unittest.TextTestRunner()
runner.run(suite)

简单的说,1>构造TestCase(测试用例),其中的setup和teardown负责预处理和善后工作。2>构造测试集,添加用例3>执行测试需要说明的是测试方法,在Python中有N多测试函数,主要的有:
TestCase.assert_(expr[, msg])
TestCase.failUnless(expr[, msg])
TestCase.assertTrue(expr[, msg])
TestCase.assertEqual(first, second[, msg])
TestCase.failUnlessEqual(first, second[, msg])
TestCase.assertNotEqual(first, second[, msg])
TestCase.failIfEqual(first, second[, msg])
TestCase.assertAlmostEqual(first, second[, places[, msg]])
TestCase.failUnlessAlmostEqual(first, second[, places[, msg]])
TestCase.assertNotAlmostEqual(first, second[, places[, msg]])
TestCase.failIfAlmostEqual(first, second[, places[, msg]])
TestCase.assertRaises(exception, callable, ...)
TestCase.failUnlessRaises(exception, callable, ...)
TestCase.failIf(expr[, msg])
TestCase.assertFalse(expr[, msg])
TestCase.fail([msg])

Ⅲ 用PYTHON写脚本

importos
#在当前目录下创建文件夹
os.mkdir('newfile')
os.mkdir('newfile/commence')
#或者直接用下面这条代码一次性创建这两个文件夹
#os.makedirs('newfile/commence')

Ⅳ Python如何调用别人写好的脚本

import脚本文件名,和导入模块是一样的。

如果只是代码片段,直接复制到自己的代码中也可以。

Ⅳ python脚本第一行怎么写

python脚本第一行的写法:【#!/usr/bin/env python】。该语句告诉操作系统执行该脚本时,首先到env设置里查找python的安装路径,然后调用对应路径下的解释器程序完成操作。
脚本语言的第一行的目的就是指出,你想要你的这个文件中的代码用什么可执行程序去运行它。
(推荐教程: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脚本在关闭的时候运行一段代码

如果是命令行的,一般是捕获ctrl-c事件吧。
import signal
import sys
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()

如果是基于GUI框架开发的,都有事件触发的,你重载事件就好了。比如Qt就有closeEvent事件

Ⅶ 这段代码是什么意思这是python的一个脚本吗,这里面的call是什么意思,求大神

看样子是一个比较大的项目里的一个脚本。首先要明确这是一个windows的批处理脚本,并不是python脚本。
再大概看了下其内容,似乎是一个有关数据处理的软件(BI即商业智能),这种类似软件有可能会依赖于一些现有的数据处理库(多半是python写的),这个脚本的作用就是调用一些列工具把python代码转换成windows下的exe。

Ⅷ 关于Python中的一段为Python脚本添加行号脚本

C语言有__LINE__来表示源代码的当前行号,经常在记录日志时使用。Python如何获取源代码的当前行号?
The C Language has the __LINE__ macro, which is wildly used in logging, presenting the current line of the source file. And how to get the current line of a Python source file?

exception输出的函数调用栈就是个典型的应用:
A typical example is the output of function call stack when an exception:

python代码
File "D:\workspace\Python\src\lang\lineno.py", line 19, in <mole>
afunc()
File "D:\workspace\Python\src\lang\lineno.py", line 15, in afunc
errmsg = 1/0
ZeroDivisionError: integer division or molo by zero

那么我们就从错误栈的输出入手,traceback模块中:
Now that, Let's begin with the output of an exception call stack, in the traceback mole:

python代码
def print_stack(f=None, limit=None, file=None):
"""Print a stack trace from its invocation point.

The optional 'f' argument can be used to specify an alternate
stack frame at which to start. The optional 'limit' and 'file'
arguments have the same meaning as for print_exception().
"""
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
print_list(extract_stack(f, limit), file)

def print_list(extracted_list, file=None):
"""Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file."""
if file is None:
file = sys.stderr
for filename, lineno, name, line in extracted_list:
_print(file,
' File "%s", line %d, in %s' % (filename,lineno,name))
if line:
_print(file, ' %s' % line.strip())

traceback模块构造一个ZeroDivisionError,并通过sys模块的exc_info()来获取运行时上下文。我们看到,所有的秘密都在tb_frame中,这是函数调用栈中的一个帧。
traceback constructs an ZeroDivisionError, and then call the exc_info() of the sys mole to get runtime context. There, all the secrets hide in the tb_frame, this is a frame of the function call stack.

对,就是这么简单!只要我们能找到调用栈frame对象即可获取到行号!因此,我们可以用同样的方法来达到目的,我们自定义一个lineno函数:
Yes, It's so easy! If only a frame object we get, we can get the line number! So we can have a similar implemetation to get what we want, defining a function named lineno:

python代码
import sys

def lineno():
frame = None
try:
raise ZeroDivisionError
except ZeroDivisionError:
frame = sys.exc_info()[2].tb_frame.f_back
return frame.f_lineno

def afunc():
# if error
print "I have a problem! And here is at Line: %s"%lineno()

是否有更方便的方法获取到frame对象?当然有!
Is there any other way, perhaps more convinient, to get a frame object? Of course YES!

python代码
def afunc():
# if error
print "I have a proble! And here is at Line: %s"%sys._getframe().f_lineno

类似地,通过frame对象,我们还可以获取到当前文件、当前函数等信息,就像C语音的__FILE__与__FUNCTION__一样。其实现方式,留给你们自己去发现。
Thanks to the frame object, similarly, we can also get current file and current function name, just like the __FILE__ and __FUNCTION__ macros in C. Debug the frame object, you will get the solutions.

Ⅸ 想用python编写一个脚本,登录网页,在网页里做一系列操作,应该怎样实现

python编写一个脚本的具体操作:

1、首先,打开python并创建一个新的PY文件。

Ⅹ Python 如何写脚本

以Python2.7操作为例:

1、首先需要打开电脑桌面,按开始的快捷键,点击Python2.7如图所示的选项进入。

阅读全文

与python脚本代码片段相关的资料

热点内容
程序员的兴趣 浏览:409
华为服务器有什么好 浏览:699
程序员和测试之间的关系 浏览:945
加密蚊帐什么意思 浏览:151
javalistclear 浏览:607
哪个app上民宿多靠谱 浏览:827
重庆服务器租用哪里有云服务器 浏览:453
土星模拟器文件夹 浏览:902
文件夹文件袋文件盒 浏览:695
云服务器打开f8指令 浏览:243
盈透证券加密币 浏览:72
阿里云服务器初始密码怎么修改 浏览:266
服务器怎么设定公用网络 浏览:99
程序员自己尝尿检测出糖尿病 浏览:593
打印添加pdf 浏览:932
苹果解压专家账号 浏览:844
度晓晓app为什么关闲 浏览:228
net文件是伪编译码吗 浏览:149
伴随矩阵的matlab编程 浏览:63
单片机和h桥是什么意思 浏览:314