Python调用net user命令时如何正确传递变量设置用户全名与描述
问题解决:Python调用net user时变量无法传递的问题
错误原因
你在subprocess.run的参数列表中使用了%description%、%full_name%这类Windows Shell变量语法,但Python不会自动解析替换这些内容,且subprocess默认以列表模式传递参数(不启动Shell),导致这些字面量直接被传给net user命令,最终用户的描述和全名显示为占位符文本。
解决方案
使用Python的f-string将变量值直接嵌入到命令参数中,确保每个参数都是正确的字符串值。同时修正print语句中的变量名错误({count}应为{Count})。
修正后的关键代码
# 替换原来的subprocess.run调用行 subprocess.run([ "net", "user", user, password, "/add", f"/comment:{description}", f"/fullname:{full_name}" ], check=True) # 修正后的print语句 print(f"It's been a pleasure in helping you add these {Count} users today.")
完整修正后的脚本
import subprocess, os, sys from easygui import passwordbox print("""Hello, I am C-3PO. I understand you'd like to add some new users to your system today I'll be happy to assist you with this task.""") Count = int(input("How many users are we creating today?")) Total = 0 GroupName = input("""We want to be sure all of the new users can find each other; comradery is so important you know. Let’s create a group for them. What would you like the group to be called?""") subprocess.run(["net", "localgroup", GroupName, "/add"], check=True) total = 0 while total != Count: first_name = input("What is the first name of the user you'd like to create? ") middle_name = input("What is their middle name, if they don't have one kindly press enter. ") last_name = input("Also, may I know their last name? ") username = (first_name[0:1] + last_name) full_name = f"{first_name} {middle_name} {last_name}" password = passwordbox("What password would you like to give " + full_name + "? ") description = input("Would you like to tell me a little about " + full_name + "? If not simply press enter. ") user=username group = GroupName # 修正后的用户创建命令 subprocess.run([ "net", "user", user, password, "/add", f"/comment:{description}", f"/fullname:{full_name}" ], check=True) subprocess.run(["net", "localgroup", GroupName, user,"/add"], check=True) total += 1 # 修正变量名的print语句 print(f"It's been a pleasure in helping you add these {Count} users today.") print("I do hope you'll inform Master James of my performance.")
额外说明
- 如果
description或full_name为空字符串(用户直接按回车),net user命令会接受空的描述/全名,不会报错;若需要避免传递空参数,可以添加判断逻辑,仅当变量非空时才加入对应参数。 - subprocess的列表参数模式更安全,避免了Shell注入风险,建议保持使用这种模式而非
shell=True。
内容的提问来源于stack exchange,提问作者James Craw
相关产品推荐
相关产品推荐

