- 浏览: 461554 次
- 性别:
- 来自: 坚持零分
文章分类
最新评论
-
wzwahl36:
文章非常赞,http://www.atool.org/img2 ...
在浏览器中解析Base64编码图像 -
realyasswl:
ie sucks
IE9 媲美Firebug的强大的程序员开发工具 -
di1984HIT:
不错啊。呵呵。
MS的一些小工具 -
NothingCanBeDone:
楼主,你这Project,能放出来了,感激不尽。
[Ray Linn]用Visual Studio 2008开发IE BHO(浏览器帮助对象) 之三 -
烬难烬:
这就没了???我去....
IE9 媲美Firebug的强大的程序员开发工具
How do I make a Python script executable on Unix?
You need to do two things: the script file's mode must be executable and the first line must begin with #! followed by the path of the Python interpreter.
The first is done by executing chmod +x scriptfile or perhaps chmod 755 scriptfile.
The second can be done in a number of ways. The most straightforward way is to write
#!/usr/local/bin/python
as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform.
If you would like the script to be independent of where the Python interpreter lives, you can use the "env" program. Almost all Unix variants support the following, assuming the python interpreter is in a directory on the user's $PATH:
#! /usr/bin/env python
Don't do this for CGI scripts. The $PATH variable for CGI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter.
Occasionally, a user's environment is so full that the /usr/bin/env program fails; or there's no env program at all. In that case, you can try the following hack (due to Alex Rezinsky):
#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""
The minor disadvantage is that this defines the script's __doc__ string. However, you can fix that by adding
__doc__ = """...Whatever..."""
Why don't my signal handlers work?
The most common problem is that the signal handler is declared with the wrong argument list. It is called as
handler(signum, frame)
so it should be declared with two arguments:
def handler(signum, frame):
...
How do I test a Python program or component?
Python comes with two testing frameworks. The doctest module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring.
The unittest module is a fancier testing framework modelled on Java and Smalltalk testing frameworks.
For testing, it helps to write the program so that it may be easily tested by using good modular design. Your program should have almost all functionality encapsulated in either functions or class methods -- and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.
The "global main logic" of your program may be as simple as
if __name__=="__main__":
main_logic()
at the bottom of the main module of your program.
Once your program is organized as a tractable collection of functions and class behaviours you should write test functions that exercise the behaviours. A test suite can be associated with each module which automates a sequence of tests. This sounds like a lot of work, but since Python is so terse and flexible it's surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the "production code", since this makes it easy to find bugs and even design flaws earlier.
"Support modules" that are not intended to be the main module of a program may include a self-test of the module.
if __name__ == "__main__":
self_test()
Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using "fake" interfaces implemented in Python.
None of my threads seem to run: why?
As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.
A simple fix is to add a sleep to the end of the program that's long enough for all the threads to finish:
import threading, time
def thread_task(name, n):
for i in range(n): print name, i
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10) # <----------------------------!
But now (on many platforms) the threads don't run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn't start a new thread until the previous thread is blocked.
A simple fix is to add a tiny sleep to the start of the run function:
def thread_task(name, n):
time.sleep(0.001) # <---------------------!
for i in range(n): print name, i
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10)
Instead of trying to guess how long a time.sleep() delay will be enough, it's better to use some kind of semaphore mechanism. One idea is to use the Queue module to create a queue object, let each thread append a token to the queue when it finishes, and let the main thread read as many tokens from the queue as there are threads.
How do I parcel out work among a bunch of worker threads?
Use the Queue module to create a queue containing a list of jobs. The Queue class maintains a list of objects with .put(obj) to add an item to the queue and .get() to return an item. The class will take care of the locking necessary to ensure that each job is handed out exactly once.
Here's a trivial example:
import threading, Queue, time
# The worker thread gets jobs off the queue. When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker ():
print 'Running worker'
time.sleep(0.1)
while True:
try:
arg = q.get(block=False)
except Queue.Empty:
print 'Worker', threading.currentThread(),
print 'queue empty'
break
else:
print 'Worker', threading.currentThread(),
print 'running with argument', arg
time.sleep(0.5)
# Create queue
q = Queue.Queue()
# Start a pool of 5 workers
for i in range(5):
t = threading.Thread(target=worker, name='worker %i' % (i+1))
t.start()
# Begin adding work to the queue
for i in range(50):
q.put(i)
# Give threads time to run
print 'Main thread sleeping'
time.sleep(5)
When run, this will produce the following output:
Running worker Running worker Running worker Running worker Running worker Main thread sleeping Worker <Thread(worker 1, started)> running with argument 0 Worker <Thread(worker 2, started)> running with argument 1 Worker <Thread(worker 3, started)> running with argument 2 Worker <Thread(worker 4, started)> running with argument 3 Worker <Thread(worker 5, started)> running with argument 4 Worker <Thread(worker 1, started)> running with argument 5 ...
How do I delete a file? (And other file questions...)
Use os.remove(filename) or os.unlink(filename);
How do I copy a file?
The shutil module contains a copyfile() function.
How do I read (or write) binary data?
or complex data formats, it's best to use the struct module. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa.
For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:
import struct
f = open(filename, "rb") # Open in binary mode for portability
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)
The '>' in the format string forces big-endian data; the letter 'h' reads one "short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the string.
How do I run a subprocess with pipes connected to both input and output?
Use the popen2 module. For example:
import popen2
fromchild, tochild = popen2.popen2("command")
tochild.write("input\n")
tochild.flush()
output = fromchild.readline()
How can I mimic CGI form submission (METHOD=POST)?
I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily?
Yes. Here's a simple example that uses httplib:
#!/usr/local/bin/python
import httplib, sys, time
### build the query string
qs = "First=Josephine&MI=Q&Last=Public"
### connect and send the server a path
httpobj = httplib.HTTP('www.some-server.out-there', 80)
httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
### now generate the rest of the HTTP headers...
httpobj.putheader('Accept', '*/*')
httpobj.putheader('Connection', 'Keep-Alive')
httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
httpobj.putheader('Content-length', '%d' % len(qs))
httpobj.endheaders()
httpobj.send(qs)
### find out what the server said in response...
reply, msg, hdrs = httpobj.getreply()
if reply != 200:
sys.stdout.write(httpobj.getfile().read())
Note that in general for URL-encoded POST operations, query strings must be quoted by using urllib.quote(). For example to send name="Guy Steele, Jr.":
>>> from urllib import quote
>>> x = quote("Guy Steele, Jr.")
>>> x
'Guy%20Steele,%20Jr.'
>>> query_string = "name="+x
>>> query_string
You need to do two things: the script file's mode must be executable and the first line must begin with #! followed by the path of the Python interpreter.
The first is done by executing chmod +x scriptfile or perhaps chmod 755 scriptfile.
The second can be done in a number of ways. The most straightforward way is to write
#!/usr/local/bin/python
as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform.
If you would like the script to be independent of where the Python interpreter lives, you can use the "env" program. Almost all Unix variants support the following, assuming the python interpreter is in a directory on the user's $PATH:
#! /usr/bin/env python
Don't do this for CGI scripts. The $PATH variable for CGI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter.
Occasionally, a user's environment is so full that the /usr/bin/env program fails; or there's no env program at all. In that case, you can try the following hack (due to Alex Rezinsky):
#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""
The minor disadvantage is that this defines the script's __doc__ string. However, you can fix that by adding
__doc__ = """...Whatever..."""
Why don't my signal handlers work?
The most common problem is that the signal handler is declared with the wrong argument list. It is called as
handler(signum, frame)
so it should be declared with two arguments:
def handler(signum, frame):
...
How do I test a Python program or component?
Python comes with two testing frameworks. The doctest module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring.
The unittest module is a fancier testing framework modelled on Java and Smalltalk testing frameworks.
For testing, it helps to write the program so that it may be easily tested by using good modular design. Your program should have almost all functionality encapsulated in either functions or class methods -- and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.
The "global main logic" of your program may be as simple as
if __name__=="__main__":
main_logic()
at the bottom of the main module of your program.
Once your program is organized as a tractable collection of functions and class behaviours you should write test functions that exercise the behaviours. A test suite can be associated with each module which automates a sequence of tests. This sounds like a lot of work, but since Python is so terse and flexible it's surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the "production code", since this makes it easy to find bugs and even design flaws earlier.
"Support modules" that are not intended to be the main module of a program may include a self-test of the module.
if __name__ == "__main__":
self_test()
Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using "fake" interfaces implemented in Python.
None of my threads seem to run: why?
As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.
A simple fix is to add a sleep to the end of the program that's long enough for all the threads to finish:
import threading, time
def thread_task(name, n):
for i in range(n): print name, i
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10) # <----------------------------!
But now (on many platforms) the threads don't run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn't start a new thread until the previous thread is blocked.
A simple fix is to add a tiny sleep to the start of the run function:
def thread_task(name, n):
time.sleep(0.001) # <---------------------!
for i in range(n): print name, i
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10)
Instead of trying to guess how long a time.sleep() delay will be enough, it's better to use some kind of semaphore mechanism. One idea is to use the Queue module to create a queue object, let each thread append a token to the queue when it finishes, and let the main thread read as many tokens from the queue as there are threads.
How do I parcel out work among a bunch of worker threads?
Use the Queue module to create a queue containing a list of jobs. The Queue class maintains a list of objects with .put(obj) to add an item to the queue and .get() to return an item. The class will take care of the locking necessary to ensure that each job is handed out exactly once.
Here's a trivial example:
import threading, Queue, time
# The worker thread gets jobs off the queue. When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker ():
print 'Running worker'
time.sleep(0.1)
while True:
try:
arg = q.get(block=False)
except Queue.Empty:
print 'Worker', threading.currentThread(),
print 'queue empty'
break
else:
print 'Worker', threading.currentThread(),
print 'running with argument', arg
time.sleep(0.5)
# Create queue
q = Queue.Queue()
# Start a pool of 5 workers
for i in range(5):
t = threading.Thread(target=worker, name='worker %i' % (i+1))
t.start()
# Begin adding work to the queue
for i in range(50):
q.put(i)
# Give threads time to run
print 'Main thread sleeping'
time.sleep(5)
When run, this will produce the following output:
Running worker Running worker Running worker Running worker Running worker Main thread sleeping Worker <Thread(worker 1, started)> running with argument 0 Worker <Thread(worker 2, started)> running with argument 1 Worker <Thread(worker 3, started)> running with argument 2 Worker <Thread(worker 4, started)> running with argument 3 Worker <Thread(worker 5, started)> running with argument 4 Worker <Thread(worker 1, started)> running with argument 5 ...
How do I delete a file? (And other file questions...)
Use os.remove(filename) or os.unlink(filename);
How do I copy a file?
The shutil module contains a copyfile() function.
How do I read (or write) binary data?
or complex data formats, it's best to use the struct module. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa.
For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:
import struct
f = open(filename, "rb") # Open in binary mode for portability
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)
The '>' in the format string forces big-endian data; the letter 'h' reads one "short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the string.
How do I run a subprocess with pipes connected to both input and output?
Use the popen2 module. For example:
import popen2
fromchild, tochild = popen2.popen2("command")
tochild.write("input\n")
tochild.flush()
output = fromchild.readline()
How can I mimic CGI form submission (METHOD=POST)?
I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily?
Yes. Here's a simple example that uses httplib:
#!/usr/local/bin/python
import httplib, sys, time
### build the query string
qs = "First=Josephine&MI=Q&Last=Public"
### connect and send the server a path
httpobj = httplib.HTTP('www.some-server.out-there', 80)
httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
### now generate the rest of the HTTP headers...
httpobj.putheader('Accept', '*/*')
httpobj.putheader('Connection', 'Keep-Alive')
httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
httpobj.putheader('Content-length', '%d' % len(qs))
httpobj.endheaders()
httpobj.send(qs)
### find out what the server said in response...
reply, msg, hdrs = httpobj.getreply()
if reply != 200:
sys.stdout.write(httpobj.getfile().read())
Note that in general for URL-encoded POST operations, query strings must be quoted by using urllib.quote(). For example to send name="Guy Steele, Jr.":
>>> from urllib import quote
>>> x = quote("Guy Steele, Jr.")
>>> x
'Guy%20Steele,%20Jr.'
>>> query_string = "name="+x
>>> query_string
发表评论
-
Python Interview Questions And Answers Set - 5
2011-05-16 20:48 2444How do I send mail from a Pytho ... -
Python Interview Questions And Answers Set - 7
2011-05-16 20:45 1939The classical "Hello World ... -
Ruby对多线程的支持
2011-02-28 10:46 55871. 我们通常说的Ruby,一 ... -
Ironruby 1.1发布了....
2010-07-18 13:23 1294Ironruby是兼容ruby 1.8.6的.NET实现,自从 ... -
【系统管理】利用脚本操作VHD以及VBOX虚拟机
2010-06-17 17:10 3552做系统管理时,常常需要为网内的机器制作一些Image,利用VH ... -
[IronRuby] C# 4.0调用ActiveRecord
2010-05-19 16:44 2449DLR引擎是一个通用的平台和承载模型,使动态语言可在 Micr ... -
ironruby 控制乌龟爬
2010-05-13 22:25 1274现在可以用ironruby控制乌龟爬了 up 10 lt ... -
【乌龟爬】之.NET中的嵌入语言与宿主的交互
2010-05-11 21:47 1576这个题目已经弄清楚了,可以研究一下进阶阶段的内容了,所以改了题 ... -
利用MKMF编写Ruby的Windows扩展 之二
2010-05-06 14:39 1290先占个坑吧,回头再总结一些林林总总的东西 C:\dosbin ... -
【工作点滴】用VS 2010 编译 Ruby 1.9.1
2010-04-22 20:43 4066关键字:ruby 1.9.1 Visual studio 20 ... -
【Ray谈Ruby] 利用MKMF编写Ruby的Windows扩展 之一
2010-03-31 16:54 3396MKMF可以帮你自动成Ruby扩展库的Makefile,这样生 ... -
扩展Ironruby
2010-03-28 20:54 1397在公司里,选择ruby作为 ... -
【IronRuby】细谈Ironruby与.NET的互操作性
2009-12-02 11:30 1717作者: Ray Linn 最后更 ... -
[IronRuby] IronRuby 1.0及与.NET互操作
2009-11-24 12:09 1612ironruby 是.Net平台下的一个ruby实现,众所周知 ... -
IronRuby: Rails-Like MVC without Rails
2008-11-13 10:51 2364IronRuby是.NET下的一个Ruby ...
相关推荐
SAP Basis Interview Questions 在进行 SAP Basis 的面试准备时,面试官通常会关注应聘者对 SAP Basis 的基础知识和实践经验的理解。例如: - **问题示例**:“请简要介绍 SAP Basis 并解释它的主要功能。” - **...
从国外网站上下载的Java面试题。可以看看国外公司的Java面试常用题,以及如何用英文回答。
115-Java-Interview-Questions-and-Answers, 115 Java访谈问题和答案- 终极列表 #115-Java-Interview-Questions-and-Answers我们将讨论关于Java面试中可以使用的各种问题,以便雇主在Java和面向对象编程方面测试你的...
### 4. 面向对象编程 #### 4.1 什么是类和对象? - **类**:是一种用户自定义的数据类型,它可以包含数据成员和成员函数。 - **对象**:是类的一个实例,可以通过对象来访问类的数据成员和成员函数。 #### 4.2 ...
### Java Interview Questions and Answers #### 1. 什么是 Java?解释其含义与定义。 Java 是当今最流行的编程语言之一,在 Web 应用程序、移动应用、软件开发、游戏系统以及服务器端技术等领域扮演着重要角色。...
CISA Interview Questions and Answers学习文档手册.pdf
根据提供的文件信息,我们可以从中提炼出三个重要的面试问题及其回答策略。这不仅是对求职者面试技巧的考验,也是展示个人专业素养与职业态度的关键时刻。接下来,我们将详细解析这三个问题及如何给出恰当的回答。...
#### 4. 你为自己的职业设定了哪些具体的目标? **优秀示例回答:** 我的职业目标包括成为一名认证财务顾问,以便我可以获得更深入的金融研究分析知识,这将使我能够更好地为我的客户提供咨询服务,因为我将拥有更...
SAP ABAP Certification Review SAP ABAP Interview Questions, Answers, And Explanations.pdf
SAP SD(Sales and Distribution)是SAP ERP中的一个核心模块,主要用于管理企业的销售流程和物流配送过程。对于希望进入SAP领域的专业人士来说,掌握SD模块的相关知识非常重要。本文将基于SAP SD面试常见问题及其...
本资料“Java-Spring-Boot-Interview-Questions-and-Answers”集合了最受欢迎的Java及Spring Boot面试问题,帮助求职者准备相关面试。 一、Java基础 1. 讲解Java内存模型(JVM)的结构,包括堆内存、栈内存、方法区...
- **设置可编辑模式**: 使用 `set_read_only` 方法将 ALV 设置为可编辑模式,该方法在接口 `IF_SALV_WD_TABLE_SETTINGS` 实现类 `CL_SALV_WD_CONFIG_TABLE` 中定义。 #### 9. 如何在 WebDynpro 中导航视图 **知识...
4. XMLHttpRequest的使用,包括完成一次GET请求的步骤和错误检测。 5. 对于严格模式与混杂模式的理解,以及触发这两种模式的方法和它们之间的区别。 6. 盒模型的深入理解,包括外边距、内边距、边框之间的关系以及在...
4. **部门(Division)**:进一步细分销售区域,如产品线或服务类型。 了解这些概念对于正确配置和使用SAP CRM至关重要。 ### 创建业务伙伴 **问题:** 在SAP CRM中创建业务伙伴的具体步骤是什么? **答案与解释...
pku acm 2371 Questions and answers代码 采用二叉查找树排序,解题报告请访问:http://blog.csdn.net/china8848
Vi and Vim: Questions and Answers takes some of the best questions and answers asked on the vi.stackexchange.com website. You can use this book to look up commonly asked questions, browse questions ...
这份"ITIL Foundations V4 Real Exam Questions & Answers - PDF"压缩包文件,显然是为了帮助备考ITIL V4基础认证考试的学员准备的。 在深入讨论ITIL V4的知识点之前,先来理解一下ITIL V4的核心概念。ITIL V4引入...
《CISM Review Questions, Answers -amp- Explanations Manual 9th》是ISACA认证CISM(Certified Information Security Manager)考试的重要参考资料,它包含了针对CISM考试的全面复习问题、答案以及详尽的解释。...
4. 组件 Prop 组件 Prop 是一个自定义的属性,可以在父组件中注册,在子组件中使用。父组件可以通过 Prop 将数据传递给子组件。子组件可以使用 Prop 接收父组件传递的数据。 5. Vue.js 生命周期 Vue.js 生命周期...