从 GitHub 获取 PowerShell 脚本并执行它
Fetch PowerShell script from GitHub and execute it
运行 从 Python.
中执行 PowerShell 脚本的问题
Python本身很简单,但是好像是传入了\n
,调用的时候出错了。
['powershell.exe -ExecutionPolicy Bypass -File', '$Username = "test";\n$Password = "password";\n$URL
这是完整的代码:
import os
import subprocess
import urllib2
fetch = urllib2.urlopen('https://raw.githubusercontent.com/test')
script = fetch.read()
command = ['powershell.exe -ExecutionPolicy Bypass -File', script]
print command #<--- this is where I see the \n.
#\n does not appear when I simply 'print script'
所以我有两个问题:
- 如何在不写入磁盘的情况下将脚本正确存储为变量,同时避免
\n
?
- 从 Python 中调用 PowerShell 的正确方法是什么,以便 运行 存储在
$script
中的脚本?
我相信这是因为您正在打开 PowerShell,它会自动以特定方式对其进行格式化。
您可以执行一个 for 循环遍历命令输出并在没有 /n 的情况下打印。
- How do I correctly store the script as a variable without writing to disk while avoiding
\n
?
这个问题本质上是 this one 的重复。对于您的示例,只需删除换行符就可以了。一个更安全的选择是用分号替换它们。
script = fetch.read().replace('\n', ';')
- What is the correct way to invoke PowerShell from within Python so that it would run the script stored in
$script
?
您的命令必须作为数组传递。此外,您不能通过 -File
参数 运行 一系列 PowerShell 语句。使用 -Command
代替:
rc = subprocess.call(['powershell.exe', '-ExecutionPolicy', 'Bypass', '-Command', script])
运行 从 Python.
中执行 PowerShell 脚本的问题Python本身很简单,但是好像是传入了\n
,调用的时候出错了。
['powershell.exe -ExecutionPolicy Bypass -File', '$Username = "test";\n$Password = "password";\n$URL
这是完整的代码:
import os
import subprocess
import urllib2
fetch = urllib2.urlopen('https://raw.githubusercontent.com/test')
script = fetch.read()
command = ['powershell.exe -ExecutionPolicy Bypass -File', script]
print command #<--- this is where I see the \n.
#\n does not appear when I simply 'print script'
所以我有两个问题:
- 如何在不写入磁盘的情况下将脚本正确存储为变量,同时避免
\n
? - 从 Python 中调用 PowerShell 的正确方法是什么,以便 运行 存储在
$script
中的脚本?
我相信这是因为您正在打开 PowerShell,它会自动以特定方式对其进行格式化。
您可以执行一个 for 循环遍历命令输出并在没有 /n 的情况下打印。
- How do I correctly store the script as a variable without writing to disk while avoiding
\n
?
这个问题本质上是 this one 的重复。对于您的示例,只需删除换行符就可以了。一个更安全的选择是用分号替换它们。
script = fetch.read().replace('\n', ';')
- What is the correct way to invoke PowerShell from within Python so that it would run the script stored in
$script
?
您的命令必须作为数组传递。此外,您不能通过 -File
参数 运行 一系列 PowerShell 语句。使用 -Command
代替:
rc = subprocess.call(['powershell.exe', '-ExecutionPolicy', 'Bypass', '-Command', script])