简体   繁体   English

如何避免python在代码所在目录运行文件?

[英]How to avoid python running file in the directory where the code is located?

I'm writing a script that will download an executable from the internet, which will create more files.我正在编写一个脚本,该脚本将从 Internet 下载一个可执行文件,这将创建更多文件。 Now, if I download the file, it will be downloaded to the directory I told it, but when I open it using os.startfile(), it creates the files to the directory where the python script is located.现在,如果我下载文件,它将被下载到我告诉它的目录中,但是当我使用 os.startfile() 打开它时,它会在 python 脚本所在的目录中创建文件。 How can I avoid that?我怎样才能避免这种情况?

Do a os.chdir() before trying to run the executable:在尝试运行可执行文件之前执行os.chdir()

os.chdir('<the target folder where you want the files to be created>')
...
os.startfile('<path to where the executable was downloaded>')

Either you can move the .py file to any other directory.您可以将.py文件移动到任何其他目录。 or You can use os.chdir() to change the current working directory of the script during the runtime.或者您可以使用os.chdir()在运行时更改脚本的当前工作目录。

os.chdir('/path/to/directory')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过传递包含文件所在目录的变量名来打开文件 python? - how to open a file by passing a variable name which contains the directory where the file is located in python? 如何在Python中删除文件(位于脚本运行所在的目录中)? - How do you delete a file (located in the same directory that your script is running in) in Python? tesseract可执行文件在MacOS上的哪里,以及如何在Python中定义它? - Where is the tesseract executable file located on MacOS, and how to define it in Python? 在带有 WSL 的 VS 代码中没有运行 Python 的此类文件或目录 - No such file or directory running Python in VS Code with WSL 位于CPython源代码中的“Python的禅”在哪里? - Where is “The Zen of Python” located in the CPython source code? 将数据保存到运行当前 python 代码的另一个目录 - Saving data to the another directory from where the current python code is running 如何在我的脚本所在的目录中使用 python 脚本安装 npm 模块 - How to install npm modules using a python script in the directory where my script is located 如何从位于名为&#39;@file_directory&#39;的文件目录中的模块或具有特殊字符的目录中导入python类? - How do I import python class from a module located within file directory named '@file_directory' or directory with special characters? 在目录中运行python文件 - Running a python file in a directory 如何将VS代码工作目录更改为运行文件目录 - How to change VS code working directory to the running file directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM