【问题标题】:Running Python Scripts from Anywhere从任何地方运行 Python 脚本
【发布时间】:2020-06-22 00:22:18
【问题描述】:

我是编程新手。再试一次。

我已经能够通过更改环境变量使 Python 从 PowerShell 运行。当我尝试使用 Win + R 启动 Python 时,只有 py 启动 python。这让我很困惑。 PowerShell 和 cmd 只需键入 python 即可。

我也在努力做到这一点,以便我可以从任何地方启动一个 python 脚本。我在 Visual Studio 代码中创建了一个名为 again.py 的简单脚本,并将脚本保存在特定文件夹中。当我尝试在 VSC 中运行脚本时,我总是收到错误消息:

[Running] python -u "c:\Users\xyz\Programming\Python\again.py" 'python' is not recognized as an internal or external command, operable program or batch file.

[Done] exited with code=1 in 0.137 seconds

据我了解,如果路径中包含一个文件夹,并且调用了存储在该文件夹中的文件,则该文件/脚本应该运行。我应该可以从任何地方调用该文件,但我无法在 PowerShell 或 Run 中键入文件名并运行它。

win + R 返回:

Windows cannot find 'again.py'. Make sure you type the name correctly, and try again.

PowerShell:重新开始.py

start : This command cannot be run due to the error: The system cannot find the file specified. At line:1 char:1 + start again.py + ~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

在 cmd 中再次键入 .py 会使其运行正常。

【问题讨论】:

  • 你能在 VSC 中运行python 吗?你的实际路径是什么?
  • 对于 xyz 的用户变量变量名称PYTHON_HOME 变量值C:\Users\xyz\AppData\Local\Programs\Python\Python38 I还在系统变量中的Path中添加了;C:\Users\xyz\AppData\Local\Programs\Python\Python38
  • 以某种方式尝试使用终端启动 Python 是 VSC 失败。这就是我得到的:PS C:\Users\xyz> Start Pythonstart : This command cannot be run due to the error: The system cannot find the file specified. At line:1 char:1 + start python etcVSC 不应该只能找到 Python 吗?我如何告诉 VSC 在哪里寻找 Python?
  • 哈哈。使用 start again.py 时,这实际上会在 VSC 中启动代码。 shebang 甚至都无所谓。伙计,这是一个如此简单的程序。我很困惑为什么它不会运行。 #! python msg = "Hello World" print = ("Hello World")

标签: python powershell path


【解决方案1】:

Powershell 错误是由文件名中的空格引起的。 Powershell 查看输入start again.py,然后像这样解析它

first token on row is word "start"
    start is an alias to start-process
second token on row is "again.py"
    that will be passed as argument to start-process

最简单的解决方法是避免文件名中出现空格。请改用下划线或驼峰式大小写。即startAgain.pystart_again.py可以使用空格,但涉及到额外的引用技巧。更糟糕的是,那些依赖于外壳。 Cmd 有自己的规则,Powershell 有非常不同的规则。由于您正在学习如何编程,请考虑暂时专注于 Python,稍后再担心 shell 引用问题。

【讨论】:

  • 出于某种原因,在 PowerShell 中输入程序名称有时会返回错误。所以通常我必须在这台笔记本电脑上使用Start,或者在我的台式机上使用Start-Process。由于我正在使用这台笔记本电脑进行学习,因此该用法的一个示例是 Start Chrome 启动 Google Chrome 并启动我的简单脚本,这应该可以工作 Start again.py
猜你喜欢
  • 2013-03-06
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多