cmd执行但python os.popen和subprocess.call和subprocess.popen和os.system不执行,为什么?

时间:2016-10-27 21:36:17

标签: python

这里我的命令通过任何一种python方式在windows cmd中执行。 ' 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')
2
>>> subprocess.call('net use J: \\Purushoth-pc\d\Materials /persistent:yes', shell=True)
2
>>> 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

如何通过python运行上面的命令? 条件:不使用任何第三方模块 - 强制性

请提前帮助我理清这个问题

1 个答案:

答案 0 :(得分:0)

您的命令失败,因为它们包含反斜杠,这在Python字符串文字中具有特殊含义。特别是,网络路径开头的“\\”将变为单个“\”,使它们不再是网络路径(此替换在粘贴文本的最后一行的错误消息中可见)

你可以将所有反斜杠加倍以逃避它们(在这种情况下很快变得不可读),或者在字符串文字前放一个“r”使它成为一个“原始字符串”,它不会特别解释反斜杠。例如:os.popen(r'net use J: \\Purushoth-pc\d\Materials').read()