[英]Powershell script equivalent of Unix “shell function”
這基本上是從Bash腳本更改當前目錄的副本,除了我在Windows上並且希望能夠從powershell腳本更改我的命令行目錄。
我實際上是從powershell文件運行python腳本,從該python腳本解析輸出目錄,然后使用該輸出作為dir更改為,所以如果有一種方法可以在python腳本中執行此操作而不是powershell文件加分!
要100%清除,是的,我知道“cd”和“os.chdir”,並且這不是我想要的 - 只會更改腳本或批處理文件的當前目錄,而不是您正在運行的命令行!
代碼如下(批處理文件是我的第一次嘗試,我希望它是PS1腳本):
sw.bat - 父目錄添加到sys $ PATH
@echo off
set _PY_CMD_="python C:\code\switch\switch.py %*"
for /f "tokens=*" %%f in ('%_PY_CMD_%') do (
cd /d %%f
)
switch.py
import os
import argparse
LOCAL = r'C:\code\local'
def parse_args():
parser = argparse.ArgumentParser(description='Workspace manager tool.')
parser.add_argument('command', type=str, help='The command to execute, or workspace to switch to.')
return parser.parse_args()
def execute_command(command):
if command in ['l', 'local']:
print(LOCAL)
def main():
args = parse_args()
execute_command(args.command)
if __name__ == '__main__':
main()
如果我的問題是正確的,那么簡單的方法就是使用[SS64]:FOR / F.
script.py :
target_dir = r"C:\Program Files"
print(target_dir)
script.bat :
@echo off
set _PY_CMD="e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" script.py
for /f "tokens=*" %%f in ('%_PY_CMD%') do (
pushd "%%f"
)
輸出 :
[cfati@CFATI-5510-0:e:\\Work\\Dev\\StackOverflow\\q057062514]> ver Microsoft Windows [Version 10.0.18362.239] [cfati@CFATI-5510-0:e:\\Work\\Dev\\StackOverflow\\q057062514]> script.bat [cfati@CFATI-5510-0:C:\\Program Files]> [cfati@CFATI-5510-0:C:\\Program Files]> popd [cfati@CFATI-5510-0:e:\\Work\\Dev\\StackOverflow\\q057062514]>
備注 :
cd /d %%f
@ EDIT0 :
最初,問題僅針對批量 ,之后添加了PowerShell ( PS )要求(可以作為一個不同的問題)。
無論如何,這是一個簡單的(虛擬)腳本,可以解決問題(我不是PS專家)。
script.ps1 :
$PyCmdOutput = & 'e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe' 'script.py'
Set-Location $PyCmdOutput
輸出 :
PS E:\\Work\\Dev\\StackOverflow\\q057062514> .\\script.ps1 PS C:\\Program Files>
在Python中嘗試os.chdir
:
os.chdir(路徑)
Change the current working directory to path. Availability: Unix, Windows.
如果你想純粹批量進行目錄更改,我會怎么做:
創建一個主目錄Var您正在調用Python的批處理文件。 SET homeDir=%cd%
然后使用cd進入所需目錄。 程序進入目錄后,使用start "Title here (optional)" cmd.exe
創建一個新的命令提示符
最后,使用cd“%homeDir%”返回主目錄
該腳本可能如下所示:
@echo off
REM using cd with no arguments returns the current directory path
SET homeDir=%cd%
REM set home Directory
cd "%desiredDirectory%"
REM moved directory
start "thisIsAName" cmd.exe
REM created new "shell" if you will
cd "%homeDir%"
REM returned to home directory
pause
在CristiFati的幫助下,我在批處理文件中使用了它。 該解決方案已發布在問題中。 經過一些谷歌搜索,我已經將批處理文件解決方案翻譯成Powershell腳本解決方案,如下所示:
$command = "& python C:\code\switch\switch.py $args"
Invoke-Expression $command | Tee-Object -Variable out | Out-Null
set-location $out
Python文件無需更改。 注意 - 這個答案是為那些想要接受python腳本的任意數量的參數並在調用python腳本時抑制stdout的人提供的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.