Purushothaman R Purushothaman R - 1 year ago 88
Python Question

cmd executes but python os.popen and subprocess.call and subprocess.popen and os.system does not execute, why?

here my command to execute in windows cmd through any of one python way.
'net use J: \My-PC\d\SharedFolder'

>>> print os.popen('net use').read()
New connections will be remembered.

Status Local Remote Network

OK M: \\Purushoth-pc\d\marriagePhotosCh
Microsoft Windows Network
OK N: \\Purushoth-pc\d\Materials
Microsoft Windows Network
The command completed successfully.

>>> print os.popen('net use J: \\Purushoth-pc\d\Materials').read()

>>> subprocess.Popen('net use J: \\Purushoth-pc\d\Materials', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
('', 'System error 67 has occurred.\r\n\r\nThe network name cannot be found.\r\n\r\n')
>>> os.system('net use J: \\Purushoth-pc\d\Materials')
>>> subprocess.call('net use J: \\Purushoth-pc\d\Materials /persistent:yes', shell=True)
>>> subprocess.check_call('net use J: \\Purushoth-pc\d\Materials /persistent:yes', shell=True)

Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
subprocess.check_call('net use J: \\Purushoth-pc\d\Materials /persistent:yes', shell=True)
File "C:\Python27\lib\subprocess.py", line 541, in check_call
raise CalledProcessError(retcode, cmd)
CalledProcessError: Command 'net use J: \Purushoth-pc\d\Materials /persistent:yes' returned non-zero exit status 2

how can i run this above command through python?
condition: without using any third party modules - mandatory

Please help me to sort out this problem, thanks in advance

Answer Source

Your commands are failing because they contain backslashes, which have a special meaning in Python string literals. In particular, the "\\" at the start of your network paths is getting turned into a single "\", making them no longer a network path (this substitution is visible in the error message on the last line of your pasted text).

You can either double all the backslashes to escape them (which quickly gets unreadable in cases like this), or put an "r" in front of the string literal to make it a "raw string" which doesn't specially interpret backslashes. For example: os.popen(r'net use J: \\Purushoth-pc\d\Materials').read()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download