46
#!/usr/bin/python3
username = 'joe'

# generate passphrase
pw_length = 6
phrase = subprocess.check_output(['pwgen', str(pw_length), '1'])
phrase = phrase.decode('utf-8').strip()

dev_null = open('/dev/null', 'w')
passwd = subprocess.Popen(['sudo', 'passwd', user], stdin=subprocess.PIPE,
                          stdout=dev_null.fileno(),
                          stderr=subprocess.STDOUT)
passwd.communicate( ((phrase + '\n')*2).encode('utf-8') )
if passwd.returncode != 0:
    raise OSError('password setting failed')

how do i fix this error :

bash-3.00# python ./pass2.py
Traceback (most recent call last):
  File "./pass2.py", line 6, in ?
    phrase = subprocess.check_output(['pwgen', str(pw_length), '1'])
NameError: name 'subprocess' is not defined
Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105
munish
  • 4,505
  • 14
  • 53
  • 83

1 Answers1

85

Subprocess is a module. You need to import it.

Put this as the second line in your file: import subprocess

jeffknupp
  • 5,966
  • 3
  • 28
  • 29
  • 1
    now i am getting this `phrase = subprocess.check_output(['pwgen', str(pw_length), '1']) AttributeError: 'module' object has no attribute 'check_output'` – munish Jan 29 '13 at 19:16
  • 1
    @munish Start a new question. Don't just edit your original question to ask a new one once the initial question was solved. You should accept jknupp's answer and ask a new question about your `check_output' error. I rolled back your edit so you could ask a new question. – Ricardo Altamirano Jan 29 '13 at 19:26
  • 4
    @RicardoAltamirano,munish: Actually, he shouldn't. He shouldn't get into the habit of posting on stackoverflow as soon as he runs into an error. But I'm with you on not continuing the other discussion here (this is mainly directed at the OP of course :p). – keyser Jan 29 '13 at 19:39
  • @Keyser Good point. Debugging should always come before posting on here. – Ricardo Altamirano Jan 29 '13 at 20:22