run perforce sync though script after changing directory

55 Views Asked by At

I am trying to sync the perforce code using automation script. I have a directory where /opengrok/src/<project_name> where .p4config is there.

But when I run below code it fail because it takes current working directory as the script's directory:

def sync_perforce_code(project_name, p4port, p4user, p4client, p4view):
    project_name = project_name
    project_dir = os.path.join("/opengrok/src", project_name)
    os.environ["P4CONFIG"] = ".p4config"
    # Run the p4 sync command
    try:
        output = os.chdir(project_dir)
        print(os.getcwd())
        subprocess.run(["p4", "info"])
        print("Successfully synced Perforce code")
    except subprocess.CalledProcessError as e:
        print(e)

print(os.getcwd()) prints correct directory but p4 info prints wrong current directory.

User name: my_username
Client name: hostname (illegal)
Client host: hostname.example.com
Client unknown.
Current directory: /script's directory/sync_code
...

Any help highly appreaciated.

1

There are 1 best solutions below

0
Samwise On

p4 defaults to PWD for interpreting relative paths. You can override the directory with the "-d" global flag:

subprocess.run(["p4", "-d", os.getcwd(), "info"])