【问题标题】:"str.split()" method returns "[0]" instead of splitting the string"str.split()" 方法返回 "[0]" 而不是拆分字符串
【发布时间】:2020-12-09 23:28:17
【问题描述】:

我正在尝试使用 os.system 拆分从 cmd 获取的字符串,但无论我拆分什么,它总是返回 [0]

import os

username = os.system("whoami /user")
username = (str(username).split(' '))

print(username)

由于某种原因,原始输出被视为整数,但这似乎并不重要,因为它被转换为字符串。

string = "This is a string"
print(string.split(' '))

尽管如此!

【问题讨论】:

  • 如果你打印出str(username),你会得到什么?这可能会帮助您找出问题所在。
  • 您得到的是命令的返回码 (0),而不是命令的标准输出

标签: python python-3.x list split


【解决方案1】:

os.system 返回命令的退出代码,而不是输出。请参阅this question 了解更多详细信息(以及确实实际获得输出的代码)。你不需要运行命令来获取用户名,只需使用getpass.getuser()

import getpass
username = getpass.getuser()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多