从 DOS 或 python shell 运行不带路径名的 python 脚本
我试图编辑注册表,因此当我输入 python shell 或 DOS 窗口时:
python sample.py
我希望它转到我保存 .py 文件的目录并运行该文件,而无需我输入:
python C:\PythonPractice\sample.py
有什么想法吗?
I was attempting to edit the registry so when I type into either the python shell or a DOS window:
python sample.py
I want it to go to the directory that I save my .py files to and run the file without me having to type:
python C:\PythonPractice\sample.py
any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 DOS 窗口:
因此,对于您的示例,您可以执行以下操作:
您可以通过转到“控制面板”>>“系统”>>“高级系统设置”>>“环境变量”来永久设置此设置。您可能想要向您的帐户添加一个变量,除非您希望它影响所有系统配置文件。可能需要重新启动。
For the DOS window:
So for your example you could do this:
You can setup this permanently by going to "Control Panel">>"System">>"Advanced system settings">>"Environment Variables". You probably want to add a variable to your account, unless you want it to affect all of the system profiles. A restart is probably required.
将其另存为
py.bat
并保存在PATH
上的目录中。将 c:\py 更改为脚本的目录。您可以从任何地方调用脚本,如下所示:
Save that as
py.bat
in a dir on yourPATH
. Change c:\py to the directory of your scripts.You can call your scripts from everywhere like this:
对 Jacob 的答案稍作改进:
将其另存为 PATH 环境变量中的目录之一中的 py.cmd 。然后你可以
使用任意数量的参数来调用This Works。
但是,正如 wberry 提到的,如果确实需要,您也可以从 Python 脚本内部更改工作目录(但我认为这是一个坏主意):
虽然这并不完全是您问题的答案,但我建议使用以下模式:
假设我有一个 Python 脚本 c:\mydir\myprog.py ,它需要特殊的环境变量(PATH、ORACLE_HOME 等),并且可能需要特定的工作目录。
然后我在同一目录中创建一个文件 myprog.cmd:
pushd/popd 部分用于更改和恢复工作目录。
有关 %~... 语法的说明,请
在命令提示符下键入。
这种方法使您可以完全控制 Python 程序的环境。
请注意,Python 调用是通用的:如果您需要第二个 Python 脚本 otherprog.py,则只需将 myprog.cmd 的副本保存为 otherprog.cmd。
A slight improvement to Jacob's answer:
Save this as py.cmd in one of the directories from your your PATH environment variable. Then you can call
This works with any number of arguments.
But, as wberry mentioned, you could change the working directory from inside your Python script as well, if you really need to (but I think that's a bad idea):
While this isn't exactly an answer to your question, I recommend using the following pattern:
Say, I have a Python script c:\mydir\myprog.py that requires special environment variables (PATH, ORACLE_HOME, whatever) and maybe it needs a particular working directory.
Then I create a file myprog.cmd in the same directory:
The pushd/popd part is for changing and restoring the working directory.
For an explanation of the %~... Syntax, type
at the command prompt.
This approach gives you full control about the environment of your Python program.
Note that the python call is generic: If you need a second Python script otherprog.py, then just save a copy of myprog.cmd as otherprog.cmd.