Configure IPython to use powershell instead of cmd

后端 未结 3 836
青春惊慌失措
青春惊慌失措 2021-02-19 10:45

Searched for this, and couldn\'t seem to find anyone who\'d already asked, so here goes.

I\'m starting to switch over to IPython as my go-to shell on Windows 7, and I\'d

相关标签:
3条回答
  • 2021-02-19 11:05

    You can use IPython's script magics to execute PowerShell commands.

    Define Magics

    In your IPython profile, modify ipython_config.py to include the lines:

    c.ScriptMagics.script_magics = ['powershell']
    c.ScriptMagics.script_paths = {
            'powershell':'powershell.exe -noprofile -command -'}
    

    -command - tells PowerShell to execute the stdin text as the command. You can leave out the -noprofile if you need to load your PS profile, but it will be slower.

    You can then use %%powershell as a script cell magic.

    In [1]: %%powershell
       ...: 1..5
    1
    2
    3
    4
    5
    

    Custom Magics

    To make it a little easier to use, I defined my own magic function to handle PowerShell commands with both line and cell magics. (see: defining your own magics) This can be loaded automatically by placing the script in your IPython profile's startup folder. (i.e. ~\.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)
    

    Usage Examples

    To use the %ps line magic and return the output to a variable:

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

    To use the %%ps cell magic and output to the console:

    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
    

    Cell magics can send output to a variable with --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'],
     ...
    
    0 讨论(0)
  • 2021-02-19 11:13

    The simplest way is to import os and update environment variable comspec in your Jupiter notebook or python shell

    import os
    os.environ['comspec']='powershell.exe'
    os.getenv('comspec')
    

    Then use following command.

    !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
    

    and more at https://ss64.com/ps/

    0 讨论(0)
  • 2021-02-19 11:21

    It is a little bit dodgy, but you could resort to calling pre-made powershell scripts using

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

    or individual commands like so:

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

    EDIT:

    I just tested this, and it seems to only have to open a single powershell instance:

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

    but I guess it could get ugly and slow if you had to call this type of thing many times in a script.

    0 讨论(0)
提交回复
热议问题