pythonnetwork-drivenet-use

"net use" didn't work in Python 3 script


I want to access some files in my network drive. My network drive is called "networkfile". If I just run this on the Window command line, it is working: net use \networkfile\Programs.

However, It didn't work when I put it in the Python script (I'm using Python3). I tried:

a = os.system("net use O:\networkfile\Programs")

a = os.system("net use \networkfile\Programs")

a = os.system("net use \networkfile\Programs")

a = subprocess.run("net use O:\networkfile\Programs", shell=True, stdout=subprocess.PIPE)

None of those work. The error is: "System error 67 has occurred. The network name cannot be found."

Anyone has experienced this before? Please advice.

Thanks,


Solution

  • your string "net use O:\networkfile\Programs" is being evaluated by the python interpreter as:

    net use O:
    etworkfile\Programs
    

    because the \n is interpreted as a newline character. You can work around this in a couple different ways

    1. use a raw string (see four paragraphs down here) to prevent backslashes being treated specially (in most cases).

    2. escape the backslashes themselves so they evaluate to a literal backslash (make all "\" into "\\")

    3. use the os.path library to generate the string so the correct directory separator is used regardless of operating system.