【问题标题】:Why putting a / and " within a subprocess won't work?为什么在子进程中放置 / 和 " 不起作用?
【发布时间】:2018-11-23 10:56:53
【问题描述】:

我正在尝试在 python 中执行一个 dos 命令,例如“date /t”。 我将它分配在 a =“日期/t”上。然后执行 subprocess.check_output(a)。然后打印(a)。 在此之前,我导入了子流程模块。 但是当我执行它时,我收到如下错误。 请帮忙。 谢谢!

【问题讨论】:

  • Traceback(最近一次调用最后):文件“C:\Python notes\func-2.py”,第 3 行,在 subprocess.check_output(a) 文件“C:\Python27 \lib\subprocess.py",第 212 行,在 check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) 文件 "C:\Python27\lib\subprocess.py",第 390 行,在 init errread, errwrite) File "C:\Python27\lib\subprocess.py", line 640, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified
  • 请提供Minimal, Complete, and Verifiable example,以及您遇到的错误。
  • 将例外编辑到您的问题中,不要放在评论中。
  • 另外,请告诉我们为什么您认为引号或斜线是罪魁祸首。最有可能的是,您使用 subprocess 的方式是将整个字符串 a 解释为要运行的 program 而不是要执行的 command DOS。但如果没有 MVCE,我们只能猜测。向我们展示您的代码!

标签: python subprocess


【解决方案1】:

Windows 中的date 不是程序,它是一个shell 命令。所以你要启动的进程就是shell。

r = subprocess.check_output('date /t', shell=True)
print r

【讨论】:

  • 谢谢!有用。这个怎么样: reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings" |查找 /i "自动"
  • @sunnyvalecalifornia 您不必执行外部程序并启动新的 shell 进程只是为了读取注册表! Python可以使用winreg模块直接读取注册表!示例:import winreg; print(winreg.ConnectRegistry(winreg.HKEY_CURRENT_USER).OpenKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings')) 请参阅 docs.python.org/3/library/winreg.html 中的文档,如果遇到困难,请提出其他问题!
  • 谢谢@nosklo。这是我的代码:def AutoConfigURL(): hKey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,"Software\Microsoft\Windows\CurrentVersion\Internet Settings") result = _winreg.QueryValueEx(hKey, "AutoConfigURL") return result[0]
猜你喜欢
  • 1970-01-01
  • 2020-05-29
  • 2016-08-15
  • 2013-06-18
  • 2019-04-07
  • 2017-04-17
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多