taskset - python的使用

3 投票
4 回答
9257 浏览
提问于 2025-04-17 14:52

我有一台双四核的电脑,所以我的CPU编号是0到7。

我正在尝试从Python中运行taskset这个命令。

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是可用的,我可以从命令行运行同样的东西。

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

我不知道问题出在哪里……

有没有什么提示?

4 个回答

2

从Python 3.3开始,sched_setaffinity及其相关功能已经成为os模块的一部分。

8

你可以不使用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)
>>>
4

跟你发的命令行比起来,你少了几个空格……比如:

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 注入攻击。

撰写回答