草庐IT

python - 相当于 Unix "shell function"的 Powershell 脚本

coder 2024-06-18 原文

这基本上是 Change the current directory from a Bash script 的副本,除了我在 Windows 上并且希望能够从 powershell 脚本更改我的命令行目录。

我实际上是从 powershell 文件运行一个 python 脚本,从该 python 脚本解析输出目录,然后使用该输出作为要更改的目录,所以如果有办法从 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
)

开关.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 .

脚本.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]>

注意事项:

  • 我使用了pushd(而不是cd),因为简单的popd 会返回到原始目录。缺点是必须记住(堆栈)他们调用了多少次 pushd 才能匹配对应的 popd。如果要切换到 cd,请像这样使用:cd/d %%f

@EDIT0:

一开始,问题只针对batch,之后是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 - 相当于 Unix "shell function"的 Powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57062514/

有关python - 相当于 Unix "shell function"的 Powershell 脚本的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  5. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  6. ruby-on-rails - 独立 ruby​​ 脚本的配置文件 - 2

    我有一个在Linux服务器上运行的ruby​​脚本。它不使用rails或任何东西。它基本上是一个命令行ruby​​脚本,可以像这样传递参数:./ruby_script.rbarg1arg2如何将参数抽象到配置文件(例如yaml文件或其他文件)中?您能否举例说明如何做到这一点?提前谢谢你。 最佳答案 首先,您可以运行一个写入YAML配置文件的独立脚本:require"yaml"File.write("path_to_yaml_file",[arg1,arg2].to_yaml)然后,在您的应用中阅读它:require"yaml"arg

  7. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  8. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  9. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  10. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

随机推荐