我在Python的文档中找到了以下示例。
#!/bin/bash
ascii=
index=0
noNames=16 #No of names to generate
nameLength=10 #Length to generate (you said 10)
for(( i=65; i<=90; i++ )) #Add upper-case letters to 'ascii'
do
ascii[$index]=$(echo $i | awk '{printf("%c",$1)}')
index=$(( $index + 1 ))
done
for(( i=48; i<=57; i++ )) # Add numbers to 'ascii'
do
ascii[$index]=$(echo $i | awk '{printf("%c",$1)}')
index=$(( $index + 1))
done
for(( i=0; i<$noNames; i++))
do
name= #We'll store the name in here
last= #We'll store the index of the last
# character generated here
for(( j=0; j<$nameLength; j++))
do
num=$(( $RANDOM % $index )) # Pick a random character index
while [[ $num -eq $last ]] #If it's the same as the last
# one...
do
num=$(( $RANDOM % $index )) #... pick a new one!
done
last=$num #Update "last" to current value
name=${name}${ascii[$num]} #Add the correct letter to our name
done
echo "${name}" #Print name...
done > output #...to our output file
但是,只有在脚本中定义代码时才有效。如何测试Python repl中定义的函数?希望有人可以指出我正确的方向。以下是我的测试。
def test():
"""Stupid test function"""
L = []
for i in range(100):
L.append(i)
if __name__ == '__main__':
import timeit
print(timeit.timeit("test()", setup="from __main__ import test"))
答案 0 :(得分:3)
如果您正在运行一个名为REPL的交互式控制台会话,它是__main__
模块:
In [228]: def x():print "foo"
In [229]: from __main__ import x
In [230]: x()
foo
也就是说,在IPython中,默认情况下有timeit
magic命令在交互命名空间中运行代码,这样就无需输入设置代码。