[英]Run Python Script From Script Directory/Current Directory
[介绍]
你好! 我正在编写一个 python 脚本来自动安装 UWP-Apps,我已经很久没有接触 Python 了; 直到今天。 该脚本使用脚本目录中的依赖项,我查看了我的旧脚本并找到了这个特定的代码。
os.chdir(os.path.dirname(sys.argv[0]))
[问题]
但是,使用上面的代码不适用于我当前的脚本,但在旧脚本上运行良好。 在上面使用时,它显示:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
已经在互联网上查找有关此主题的信息; 但他们中的大多数人都在谈论从外部/不同目录运行脚本,这导致我陷入死胡同。
任何帮助表示赞赏:)
.py
文件:cd path/to/python/file && python ../.py
在运行 puthon 脚本的目录中将其另存为runPython.sh
:
#!/bin/sh
cd path/to/python/file
python ../script.py
使其可执行:
chmod +x ./runPython.sh
然后你可以简单地进入你的目录并运行它:
./runPython.sh
mydir = os.getcwd() # would be the folder where you're running the file
mydir_tmp = "path/to/python/file" # get the path
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd()
您收到错误的原因是因为sys.argv[0]
是文件本身的名称,您可以将目录作为字符串传递并使用sys.argv[1]
代替。
import os
from os.path import abspath, dirname
os.chdir(dirname(abspath(__file__)))
可以使用dirname(abspath(__file__)))
获取python脚本的父目录,将os.chdir
放入其中,使脚本在其所在目录运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.