检查特定Python脚本是否已在Windows中运行的最佳/最简单的原因是什么?
我有一个脚本遍历文件夹中的所有文件并将它们复制到另一个文件夹(排序到电影或电视节目文件夹)。我想确保脚本何时启动,没有另一个已经运行的进程(相同的脚本),所以我不会遇到试图移动相同文件的2个脚本的问题。
我试图在脚本的开头创建一个文件,并在脚本完成时删除它,但是当脚本崩溃和/或抛出错误时我遇到了问题。
我知道我可以使用psutil,但后来我将获得进程名称(python.exe),我正在寻找一个原因来区分Python进程是运行我的脚本还是其他程序。
对于Windows o.s.你可以使用timestamp.txt文件
timestamp = 'timestamp.txt'
...
elif windows:
try:
new_timestamp = False
if not os.path.exists(timestamp):
new_timestamp = True
try:
with open(timestamp, 'a') as f_timestamp:
f_timestamp.write(str(int_t0))
except IOError as e:
out1 = 'M. Cannot open file for writing. Error: %s - %s.' \
% (e.logfile, e.strerror) + ' -> Exit code 3'
logging.error(out1)
sys.exit(3)
if not new_timestamp and os.path.exists(timestamp):
out1 = 'N. Script ' + __file__ + ' is already running.'
print(out1)
logging.error(out1)
sys.exit(0)
except IOError as e:
out1 = 'J. Cannot open file. Error: %s - %s.' \
% (e.filepath, e.strerror) + ' -> Exit code 4'
logging.error(out1)
...
try:
f_timestamp.close()
os.remove(timestamp)
except OSError as e:
logging.error('B. Cannot delete ' + timestamp + \
' Error: %s - %s.' % (e.filename, e.strerror))
您可以使用psutil.Process().cmdline()
查看进程的完整命令行。
或者,您可以锁定正在处理的文件。请参阅this question的答案,如何在ms-windows上执行此操作。带锁的东西是你必须小心删除它们,尤其是在发生错误时。
使用lockfile。它是跨平台的,使用本机OS功能,并且比任何home-brewn锁文件创建模式更健壮
我用一个空的虚拟文件解决了它。在进程开始时,我检查文件是否存在,如果不是,我创建一个新文件,运行该进程并最终将其删除(即使进程失败),如果文件确实存在,则意味着该进程是现在运行,所以我终止当前(新)进程。