0

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

  • What exactly do you need help with? If this code is not working as expected, please give details. Are you getting errors, or incorrect results? – John Gordon Mar 09 '22 at 20:27
  • This code gives me this error, File "loginscript.py", line 11 subprocess.run(['useradd',input=word , shell=True ]) ^ SyntaxError: invalid syntax – thelinuxman Mar 10 '22 at 07:13
  • Your indentation is clearly wrong; please [edit] to fix it. On the desktop version of this site, paste your code, then select the pasted block and type ctrl-K to correctly format your code with indentations preserved. – tripleee Mar 10 '22 at 08:19

1 Answers1

0

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318