繁体   English   中英

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

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

在这里,我的命令可以通过任何一种python方式在Windows cmd中执行。 净使用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运行以上命令? 条件:不使用任何第三方模块-强制性

请帮助我解决这个问题,在此先感谢

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

您可以将所有反斜杠加倍以使其转义(在这种情况下,它们很快就会变得不可读),也可以在字符串文字前加上“ r”,使其成为不专门解释反斜杠的“原始字符串”。 例如: os.popen(r'net use J: \\\\Purushoth-pc\\d\\Materials').read()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM