Category Archives: Python

Run Shell Command And Capture Output in Python

To run a shell command and capture the output in Python, use: import subprocess   batcmd="ls"   result = subprocess.check_output(batcmd, shell=True)import subprocess batcmd="ls" result = subprocess.check_output(batcmd, shell=True) With “shell=True” you will get the same behavior as os.system(). To capture the strerr use: result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)

Python Iterate over a List in Chunks

Here is a function that iterates a list in chunks: # (in python 2 use xrange() instead of range() to avoid allocating a list) def chunker(seq, size): return (seq[pos:pos + size] for pos in range(0, len(seq), size))# (in python 2 use xrange() instead of range() to avoid allocating a list) def chunker(seq, size): return (seq[pos:pos […]

Run Processes in Parallel in Python

Today I found a nice example to run processes in parallel in python: import os from multiprocessing import Pool     processes = (‘process1.py’, ‘process2.py’, ‘process3.py’)     def run_process(process): os.system(‘python {}’.format(process))     pool = Pool(processes=3) pool.map(run_process, processes)import os from multiprocessing import Pool processes = (‘process1.py’, ‘process2.py’, ‘process3.py’) def run_process(process): os.system(‘python {}’.format(process)) pool = […]

How to Terminate a Python Script

The simplest way is to use quit(), i.e: // do something   quit()// do something quit() Another way is to use sys.exit(), i.e: import sys sys.exit()import sys sys.exit()

Read File Line by Line in Python

Example to read a file line by line in python: testsite_array = [] with open(‘file.txt’) as my_file: for line in my_file: testsite_array.append(line)testsite_array = [] with open(‘file.txt’) as my_file: for line in my_file: testsite_array.append(line) Alternatively, you may want to use f.readlines(): with open(‘file.txt’) as my_file: testsite_array = my_file.readlines()with open(‘file.txt’) as my_file: testsite_array = my_file.readlines()

Run Python Scripts Without Invoking `Python`

To nromally run python scriupts you need to invoke `python`, i.e: python script.pypython script.py However, if you include this text in the first line of your python script: #!/usr/bin/python#!/usr/bin/python Then you can run your python script with just: ./script.py./script.py Of course, you’ll need to first set +x permissions: chmod +x script.pychmod +x script.py If you […]

How to Install Python PIP on Debian

To manage Python packages you can use PIP. To install PIP just type: apt-get install python-pip #python 2 apt-get install python-pip3 #python 3apt-get install python-pip #python 2 apt-get install python-pip3 #python 3 Here is an example on how to use PIP: pip install packageName pip uninstall packageName pip search packageNamepip install packageName pip uninstall packageName […]