【问题标题】:Dictionary items not working when passed through powershell command通过powershell命令时字典项不起作用
【发布时间】:2016-07-02 12:18:56
【问题描述】:

我有一个从包含桌面链接的 .txt 文件创建的字典。我需要将这些链接插入到 powershell 命令中。但是,当我使用 '%s' % my_data[key] 时,我得到了额外的反斜杠,因此 powershell 不会处理该命令,因为它不知道要查找什么,我该如何删除额外的反斜杠?

['powershell.exe', "$sh = New-Object -COM WScript.Shell\n$sh.CreateShortcut('C:\\Users\\johns\\desktop\\python\\Survey+Update\\testing this shared.lnk\n').TargetPath"]

【问题讨论】:

  • 你粘贴的那个字典在你的 Python 代码中有一个变量,对吧?
  • 是的,因为当我运行它时,它就会出现。完整的命令如下所示。 ([r"powershell.exe", "$sh = New-Object -COM WScript.Shell" + "\n" + "$sh.CreateShortcut('%s').TargetPath" % (my_data[key])] )
  • 关于它,给我一分钟
  • 你是如何将这个发送到 powershell 的?
  • subprocess.Popen([r"powershell.exe", "$sh = New-Object -COM WScript.Shell" + "\n" + "$sh.CreateShortcut(%s).TargetPath " % my_data[key]], stdout=subprocess.PIPE).communicate()[0]

标签: python python-2.7 powershell dictionary backslash


【解决方案1】:

我发现双反斜杠不是问题。为我的代码subprocess.Popen([r"powershell.exe", r"$sh = New-Object -COM WScript.Shell" + "\n" + "$sh.CreateShortcut(%s).TargetPath" % my_data[key]], stdout=subprocess.PIPE).communicate()[0]

字典在每一行的末尾都有 \n。我用my_dict[key].replace("\n","") 摆脱了它。还需要“路径”\"%s\" 修复的路径。我不知道powershell是如何处理双反斜杠的????但它确实

【讨论】:

    【解决方案2】:

    尝试像这样使用 os.path.normpath:

    dir_file = os.path.normpath("C:/Users/johns/desktop/python/Survey+Update/testing this shared.lnk")
    ['powershell.exe', "$sh = New-Object -COM WScript.Shell\n$sh.CreateShortcut({0}).TargetPath".format(dir_file)]
    

    【讨论】:

    • 好吧,让我试试这个。
    • 该死,让我继续努力
    • 哦,我说得还不够。感谢您抽出宝贵时间。我在发帖前找了 2 天。
    • @JohnShiveley 我改变了我的答案,看看现在情况如何。不客气,希望我能解决这个问题。
    • 再看一遍,我发现这是一种不同的方法。我正在使用字典,因为我从文本文件中提取了这些路径。我需要字典中的每个项目来运行这个 powershell 脚本。 ' 对于 my_data.iteritems() 中的键、值: subprocess.Popen([r"powershell.exe", "$sh = New-Object -COM WScript.Shell" + "\n" + "$sh.CreateShortcut(% s).TargetPath" % my_data[key]], stdout=subprocess.PIPE).communicate()[0] '
    猜你喜欢
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多