配置IPython以使用powershell而不是cmd

jmw*_*lch 11 windows powershell ipython

搜索过这个,似乎找不到任何已经问过的人,所以现在就去了.

我开始在Windows 7上切换到IPython作为我的首选shell,我想配置它以便!cmd将命令传递给系统shell 的bang magic()使用PowerShell而不是cmd.exe,所以我可以利用MS所做的增强功能,但不必将我%COMSPEC%改为PowerShell(我的公司仍然使用几个基于CMD的.BAT进行自动化,我不想破坏它们).

我会在顶部发布我的问题,因为答案可能不需要以下任何信息:

  1. 我错过了什么吗?有没有办法在IPython中使用配置文件来指定系统命令解释器?
  2. 如果!1,是否有一种方法可以让我从PowerShell中启动子进程,并使用该进程本地的机器范围环境变量?

研究/测试

通过IPython代码,我看到它os.system()用于将命令发送到shell,而不是subprocess.call().这使事情变得更复杂,因为os.system*只使用COMSPEC,在子进程*中,您可以指定要使用的可执行文件.

我尝试加载PowerShell,设置$env:comspec变量,然后从该shell中启动IPython,但即使COMSPEC出现设置,即使在IPython中,看起来仍然使用CMD:

[PS] C:\> $env:comspec
C:\Windows\system32\cmd.exe
[PS] C:\> $env:comspec = 'powershell.exe'
[PS] C:\> $env:comspec
powershell.exe
[PS] C:\> & 'C:\Python33\Scripts\ipython3.exe'
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.

IPython 1.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import os; os.getenv('comspec')
Out[1]: 'powershell.exe'

In [2]: !gci
'gci' is not recognized as an internal or external command,
operable program or batch file.

In [3]: os.system('gci')
'gci' is not recognized as an internal or external command,
operable program or batch file.
Out[3]: 1
Run Code Online (Sandbox Code Playgroud)

看起来本地修改的COMSPEC正在传递给IPython(作为PowerShell进程的一个子进行本地更改),但os.system看起来仍然使用持久性设置.

我尝试了类似的东西,[Environment]::SetEnvironmentVariable("ComSpec", 'powershell.exe', [System.EnvironmentVariableTarget]::User)如果我只能改变一个用户范围的环境变量,但是这也不起作用(与上面相同的结果 - os.getenv('ComSpec')显示powershell,但是!-ed命令被发送到CMD) .

更改机器范围环境变量似乎做了我想要的,但由于前面提到的原因,它不是我的有效解决方案.

[PS] C:\> $env:comspec
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
[PS] C:\> [Environment]::GetEnvironmentVariable('ComSpec','User')
[PS] C:\> [Environment]::GetEnvironmentVariable('ComSpec','Machine')
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
[PS] C:\> & 'C:\Python33\Scripts\ipython3.exe'
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.

IPython 1.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: !gci env:ComSpec

Name                           Value
----                           -----
ComSpec                        C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
Run Code Online (Sandbox Code Playgroud)

由于这不是一个可行的持续解决方案,我通过修改ConEmu*中的设置来测试更多.我能做到这一点,而不通过设置改变全局变量明确可执行文件子进程设置COMSPEC环境变量选择的值*在标志设置>启动> COMSPEC,并提供路径powershell.exe,但我不确定这是否会对使用ConEmu打开的CMD控制台产生负面影响,因为该设置是全局的(在ConEmu内).这就是让我问上面问题2的原因,因为我不确定如何在PowerShell中设置进程/子局部,机器范围环境变量(如果这样的话甚至可能).

最后,我的梦想目标是让IPython通过配置文件支持命令shell解释器的规范,但要做到这一点,os.system()不能使用它.我打算用它取代鼓捣subprocess.call()我的本地副本(网HRS欧洲这个Python的文件)来测试,但如果任何人已经与播放,或者如果超过使用有足够的优势,以目前的模式subprocess,我不是意识到,我很高兴听到它.看起来这已经在非Windows系统(GitHub)上完成了,但是我已经足够新了这个规模的Python,我不能肯定如果在Windows端使用了这个改变,那么别的什么都不会破坏有条件的,也是.

脚注

尔加!显然,必须有10+声誉才能正确记录问题.以下是我不允许在上面发布的链接:

  • os.system - docs.python.org/3.3/library/os.html#os.system
  • subprocess - docs.python.org/3.3/library/subprocess.html
  • ConEmu - code.google.com/p/conemu-maximus5/

Ryn*_*ant 8

您可以使用IPython的脚本魔法来执行PowerShell命令.

定义魔法

在您的IPython配置文件中,修改ipython_config.py以包含以下行:

c.ScriptMagics.script_magics = ['powershell']
c.ScriptMagics.script_paths = {
        'powershell':'powershell.exe -noprofile -command -'}
Run Code Online (Sandbox Code Playgroud)

-command -告诉PowerShell执行stdin文本作为命令.-noprofile如果您需要加载PS配置文件,可以省略,但速度会慢一些.

然后,您可以使用%%powershell一个脚本细胞魔法.

In [1]: %%powershell
   ...: 1..5
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

自定义魔术

为了使它更容易使用,我定义了我自己的魔术函数来处理线条和单元格魔法的PowerShell命令.(请参阅:定义自己的魔法)这可以通过将脚本放在IPython配置文件的启动文件夹中自动加载.(即~\.ipython\profile_default\startup\05-powershell_magic.py)

from IPython.core.magic import register_line_cell_magic

from IPython import get_ipython
ipython = get_ipython()

@register_line_cell_magic
def ps(line, cell=None):
    "Magic that works both as %ps and as %%ps" 
    if cell is None:
        ipython.run_cell_magic('powershell', '--out posh_output' ,line)
        return posh_output.splitlines()
    else:
        return ipython.run_cell_magic('powershell', line, cell)
Run Code Online (Sandbox Code Playgroud)

用法示例

要使用%ps魔术线并将输出返回到变量:

In [1]: ps_version = %ps $PSVersionTable.PSVersion.ToString()

In [2]: print(ps_version)
['2.0']
Run Code Online (Sandbox Code Playgroud)

要使用%%ps单元格魔术并输出到控制台:

In [3]: %%ps
   ...: gci c:\

    Directory: C:\

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d-r--         10/2/2013  10:39 AM            Program Files
d-r--         12/6/2013   1:44 PM            Program Files (x86)
d----          2/6/2014   4:33 PM            TEMP
d-r--        11/27/2013  11:10 AM            Users
d----         1/13/2014  11:21 AM            Windows
Run Code Online (Sandbox Code Playgroud)

Cell magics可以将输出发送到变量--out <variable name>:

In [4]: %%ps --out process_name_id
   ...: $procs = gps| select Name, ID
   ...: $procs| ConvertTo-Csv -NoType| select -skip 1

In [5]: import csv

In [6]: list(csv.reader(process_name_id.splitlines()))
Out[6]:
[['7+ Taskbar Numberer', '3400'],
 ['acrotray', '3668'],
 ['armsvc', '1772'],
 ['audiodg', '4160'],
 ['AutoHotkeyU64', '472'],
 ['chrome', '6276'],
 ...
Run Code Online (Sandbox Code Playgroud)


Som*_*pta 5

最简单的方法是在Jupiter笔记本或python shell中导入os并更新环境变量comspec

import os;
os.environ['comspec']='powershell.exe'
os.getenv('comspec')
Run Code Online (Sandbox Code Playgroud)

然后使用以下命令。

!gc log.txt | select -first 10 # head
!gc -TotalCount 10 log.txt     # also head
!gc log.txt | select -last 10  # tail
!gc -Tail 10 log.txt           # also tail (since PSv3), also much faster than above option
!gc log.txt | more             # or less if you have it installed
!gc log.txt | %{ $_ -replace '\d+', '($0)' }         # sed
Run Code Online (Sandbox Code Playgroud)

以及更多https://ss64.com/ps/


Vas*_*kis 0

这有点狡猾,但您可以使用调用预制的 powershell 脚本

os.system('powershell C:\file.ps1')

或像这样的单独命令:

os.system("powershell; gci | where {$_.Fullname -contains 'some stuff'}")

编辑:

我刚刚对此进行了测试,似乎只需要打开一个 powershell 实例:

os.system("powershell; gci; gc C:\windows\system32\drivers\etc\services; [system.net.dns]::gethostbyaddress('203.20.74.6') | more")

但我想如果您必须在脚本中多次调用此类事物,它可能会变得丑陋且缓慢。