python tips

 

目錄

  • "_"
  • random

 


"_" variable

 

_ has 3 main conventional uses in Python

1. To hold the result of the last executed statement

>>> 2 + 4
6
>>> _ + 4
10

2. For translation lookup in il8n

3. "throwaway" variable

for _ in range(6):
    .........

 


random

 

# Return a random integer N such that a <= N <= b

from random import randint
randint(2,9)

# Return a random element from the non-empty sequence seq

from random import choice
choice(seq)

# Return the next random floating point number in the range [0.0, 1.0).

random.random()

 


Filename

 

有 Code: subprocess.py

import subprocess

process = subprocess.Popen('ls',
              stdout=subprocess.PIPE,
              stderr=subprocess.PIPE)

執行時出 Error

AttributeError: 'module' object has no attribute 'Popen'

原因

The error message may show a stale path.

解決方案

Do not name your files the same thing as the externals you are importing.

Checking

#!/usr/bin/env python

import subprocess
print subprocess.__file__

Output

/root/test/subprocess.py