taskset - python

时间:2013-02-05 20:51:25

标签: python linux

我有一台双四核机器。所以,cpu列表给我0-7。

我正在尝试从python运行任务集

mapping = [2,2,2,2,2]
for i in range(0,len(mapping)):
        cmd = "taskset -c" +  str(mapping[r]) + "python <path>/run-apps.py" + thr[r] + "&"
        os.system(cmd)

它说:

taskset: invalid option -- '2'
taskset (util-linux-ng 2.17.2)
usage: taskset [options] [mask | cpu-list] [pid | cmd [args...]]
set or get the affinity of a process

  -p, --pid                  operate on existing given pid
  -c, --cpu-list             display and specify cpus in list format
  -h, --help                 display this help
  -V, --version              output version information

The default behavior is to run a new command:
  taskset 03 sshd -b 1024
You can retrieve the mask of an existing task:
  taskset -p 700
Or set it:
  taskset -p 03 700
List format uses a comma-separated list instead of a mask:
  taskset -pc 0,3,7-11 700
Ranges in list format can take a stride argument:
  e.g. 0-31:2 is equivalent to mask 0x55555555

但核心2可用,我将从commandline运行相同的东西。

taskset -c 2 python <path>/run-apps.py lbm &

不知道问题是什么..

任何提示?

3 个答案:

答案 0 :(得分:3)

与您发布的命令行相比,您错过了几个空格......例如:

cmd = "taskset -c " +  str(mapping[r]) + " python <path>/run-apps.py " + thr[r] + " &"

在您的代码中,在解析“命令行”时,taskset看到的字符串-c2根据许多命令行解析库与-c -2相同,这将解释错误你看到了。

如果您使用字符串插值,有时这些内容更容易阅读:

cmd = "taskset -c %s python <path>/run-apps.py %s &" % (mapping[r],thr[r])

或新款.format

cmd = "taskset -c {0} python <path>/run-apps.py {1} &".format(mapping[r],thr[r])

最后,使用os.system的解决方案应该没有至少提及python subprocess模块。

process = subprocess.Popen(['taskset',
                            '-c',
                            str(mapping[r]),
                            'python',
                            '<path>/run-apps.py',
                            str(thr[r]) ] )

它将完全避免使用shell,这样可以提高效率,并使你更容易受到shell注入类型的攻击。<​​/ p>

答案 1 :(得分:2)

您可以避免调用taskset并使用psutil: https://pythonhosted.org/psutil/#psutil.Process.cpu_affinity

>>> import psutil
>>> psutil.cpu_count()
4
>>> p = psutil.Process()
>>> p.cpu_affinity()  # get
[0, 1, 2, 3]
>>> p.cpu_affinity([0])  # set; from now on, process will run on CPU #0 only
>>> p.cpu_affinity()
[0]
>>>
>>> # reset affinity against all CPUs
>>> all_cpus = list(range(psutil.cpu_count()))
>>> p.cpu_affinity(all_cpus)
>>>

答案 2 :(得分:0)

你缺少空格。为了帮助您自己尝试以下方法:

  1. 注释掉os.system()行
  2. 在os.system()行下面,添加:

    print cmd

  3. 您将看到命令行的样子。根据需要添加空格。然后取消注释os.system()行。

相关问题