0

How to use nice in python ?

I have a simple bash script:

nice -n 9 cp /var/tmp/1 /var/tmp/2

What will be python alternative?

Bdfy
  • 23,141
  • 55
  • 131
  • 179

2 Answers2

6

In pure Python, you can use os.nice and shutil.copy (or shutil.copyfile if you do not need to preserve file metadata):

import os
import shutil

os.nice(9)
shutil.copy('/var/tmp/1', '/var/tmp/2')
Nicolas Cortot
  • 6,591
  • 34
  • 44
2

Of course, there's always os.system:

os.system("nice -n 9 cp /var/tmp/1 /var/tmp/2")

A nicer solution is to use os.nice with preexec_fn:

import subprocess, os
subprocess.Popen("cp /var/tmp/1 /var/tmp/2", shell=True, preexec_fn=lambda: os.nice(9))
nneonneo
  • 171,345
  • 36
  • 312
  • 383