0

I am relatively new to perforce. I have been asked to look into a way to automate the process of user account creation through a script. That is because during each Term we have so far been going in manually and making accounts for each new student ourselves, a process that is incredibly tedious.

I think I have a reasonably clear idea of what some of the Python code for this may look like, in terms of reading data from the spreadsheet. However, I am unsure about the second part - actually creating user accounts and tying them to the Perforce server we have. How would I go about doing that? The other thing I am confused about is how to prevent duplicate users from being made?

Here is some code for the first part of the process.

import csv

# Read in user data from the CSV file
with open('user_data.csv', 'r') as csv_file:
    reader = csv.DictReader(csv_file)
    for row in reader:
        first_name = row['First Name']
        last_name = row['Last Name']
        username = row['Username']
        email = row['Email']
        password = row['Default Password']

1 Answers1

0

With the P4Python module you can create a user with the fetch_user and save_user functions:

import csv
from P4 import P4

# Read in user data from the CSV file
with open('user_data.csv', 'r') as csv_file, P4().connect() as p4:
    reader = csv.DictReader(csv_file)
    for row in reader:
        user = p4.fetch_user(row['Username'])
        user._email = row['Email']
        user._fullname = row['First Name'] + ' ' + row['Last Name']
        user._password = row['Default Password']
        p4.save_user(user, '-f')  # -f lets an admin modify another user

Usernames are unique in Perforce's database, so it is not possible to create duplicate usernames (with the above script the last username processed would simply overwrite any previous user with that name).

If you wanted different behavior (e.g. to raise an exception when an existing user is encountered) you could add code to check for an existing user before modifying it, using p4.run_users(row['Username']) in a try/except to verify that no user is returned.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Hello Samwise! Nice to see you again. Instead of throwing an exception, is there a way to check if the user is already created and if so, move to next iteration in the loop? – Sternutation Jan 27 '23 at 18:39
  • Use the `continue` statement to move to the next iteration of a loop. Note that this just means that you'll be keeping the *first* occurrence of the user rather than the *last*. – Samwise Jan 27 '23 at 21:20
  • Thank you, basically I want to ensure that none of the usernames previously exist in the server. So I don't want them to get overwritten, nor do I want duplicates. – Sternutation Feb 03 '23 at 14:49