'python script to create user account from txt file
I am trying to learn to program. I need help to loop users from the login.txt file into this subprocess. any help would be appreciated.
with open("login.txt",'r') as file:
#reading each line
for line in file:
#reading each word
for word in line.split():
subprocess.run(['useradd',input=word , shell=True])
cat login.txt
test01
test02
test03
test04
getting this error: File "loginscript.py", line 11 subprocess.run(['useradd',input=word , shell=True ]) ^ SyntaxError: invalid syntax
Solution 1:[1]
The shell=True is doubly wrong; if you were to use it, it should go outside the first argument; but when the first argument is a list, you almost certainly don't want shell=True here at all. See also Actual meaning of shell=True in subprocess
(There are situations where shell=True make sense with a list argument, but you really need to understand what you are doing. This is slightly less weird on Windows, but only because Windows as a whole is weirder.)
Also, you probably want to omit input= in front of the word argument, and simply run
with open("login.txt",'r') as file:
for line in file:
word = line.rstrip('\n')
subprocess.run(['useradd', word], check=True)
Finally, notice also how the newline is still present when you read lines like this, and needs to be trimmed off, and how we pass in check=True to have Python raise an exception if the subprocess fails.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tripleee |
