As far as I know, petsc4py library needs to be configured to complex number mode when solving complex number problems. Now the question is, if I have both real and complex number parts in my program, I can’t use a single environment to complete the above solving process. Is my understanding correct?

Yes, that is correct. Please note that this is a pure PETSc question and is better asked to their developers. There might be ways to circumvent this by adapting petsc-arch on the fly and then re-importing petsc4py (given that it has been installed for both floating types). Allthough i have not tested this and might lead to others issues in petsc -initialization/destruction of objects.

Note that as long as the real and complex numbers have the same precision (double or single) you can solve real valued problems with a complex number representation (as the complex part will just be zero). It might restrict the choice of solvers you can use though