【问题标题】:TypeError: unsupported operand type(s) for &: 'str' and 'str' How to solve it [duplicate]TypeError:&:'str'和'str'不支持的操作数类型如何解决它[重复]
【发布时间】:2020-01-19 02:14:47
【问题描述】:

我需要知道有多少同名“chrome.exe”正在运行的进程。

这是我的python脚本

import wmi
c = wmi.WMI ()

for process in c.Win32_Process ():
    #print (process.Name)
    if process.Name == "chrome.exe" & process.Name > 1:
        print (process.Name)

当我运行这个脚本时,我会得到这样的结果:

chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe
chrome.exe

但我需要以数字形式获取数量,如果它大于 1,则打印一些内容并出现此错误

TypeError: &: 'str' 和 'str' 的操作数类型不受支持

【问题讨论】:

  • 您可能需要and 运算符而不是按位& 运算符。
  • 如果您需要对进程进行计数,请创建一个计数器变量并在循环内将其递增 1。
  • 我不清楚你想用> 1做什么。您刚刚检查了 .Name 是否等于某个字符串,接下来您要检查它是否大于 1...?!
  • @deceze 我知道这是个错误,因此我建议一些帮助

标签: python python-3.x


【解决方案1】:

天哪,这里有点乱。 问题:您需要将'&'更改为'and'

其他:

for process in c.Win32_Process (): -> for process in c.Win32_Process():

print (process.Name) -> print(process.Name)

终于:

i = 1 # or 0, do as you need
for process in c.Win32_Process():
    if process.Name == "chrome.exe" and i > 1:
        print(process.Name)
    i += 1 # there are more elegenat ways to do this, but let's keep this simple

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2018-04-22
    • 1970-01-01
    • 2013-08-18
    相关资源
    最近更新 更多