在与调用Python模块或脚本相同的目录中运行文件 [英] Running a file in the same directory as the invoking Python module or script

查看:58
本文介绍了在与调用Python模块或脚本相同的目录中运行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Python(与Python脚本位于同一目录)运行批处理文件?

How can I run a batch file with Python (in the same directory as the Python scripts)?

请注意,目录不能恒定,因为它可以从一个用户更改为另一个用户.

Note that the directory cannot be constant as it can be changed from one user to another.

推荐答案

您需要找出脚本的位置并组装绝对路径:

You need to find out where your script is and assemble an absolute path:

import os
import subprocess

dirname = os.path.dirname(os.path.abspath(__file__))
cmd = os.path.join(dirname, 'mybatch_file')

subprocess.call(cmd)

逐步

您可以通过以下方式找到脚本的名称:

In Steps

You can find out the name of script with:

__file__

现在将其设为绝对路径:

Now make it an absolute path:

os.path.abspath

并获取它所在的目录:

os.path.dirname

最后,将此路径与您的批处理文件名一起添加:

Finally, join this path with your batch file name:

os.path.join

在将其提供给:

subprocess.call

这篇关于在与调用Python模块或脚本相同的目录中运行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆