How can I write a script to take userdata from a spreadsheet and create perforce user accounts based on that data?

52 Views Asked by At

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

There are 1 best solutions below

3
Samwise On

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.