How can I get the name/file of the script from sitecustomize.py?

2024/10/11 0:29:46

When I run any Python script, I would like to see the script's filename appear in the Windows command line window's titlebar. For example, if I run a script called "mytest.py", I want to see "mytest" in the titlebar. I would like this to be automatic, so I don't have to add code to every one of my scripts.

Currently I'm attempting to do this with sitecustomize.py, because when Python is run, including from double-clicking a Python script, sitecustomize is imported before the script runs.

I've tried getting __main__'s __file__ and sys.argv, but sitecustomize doesn't see either:

file sitecustomize.py:

import __main__, sys
print "hasattr __main__.__file__:", hasattr(__main__, "__file__")
print "hasattr sys.argv:", hasattr(sys, "argv")
print "-" * 60

file mytest.py:

import sys
print "__file__ is:", __file__
print "sys.argv is:", sys.argv
raw_input() # don't end the script immediately

output:

hasattr __main__.__file__: False
hasattr sys.argv: False
------------------------------------------------------------
__file__ is: C:\Documents and Settings\Owner\Desktop\mytest.py
sys.argv is: ['C:\\Documents and Settings\\Owner\\Desktop\\mytest.py']
Answer

I'm glad you asked! I now have it working for my scripts, and it's pretty cool.

Here's the code:

import sys
import time
from ctypes import windllclass SetTitle(object):def __del__(self):time.sleep(1)command = ' '.join(sys.argv)windll.kernel32.SetConsoleTitleA(command)sys.argv = SetTitle()

This is for Python 2.x -- for 3.x you need to change SetConsoleTitleA to SetConsoleTitleW (last letter changes from A to W).

How it works: since the sys.argv object does yet exist, I create an object and assign it to sys.argv; then, when Python assigns the actual argv to sys.argv, my object is tossed, and the __del__ method is called; the __del__ method is then able to access the real argv and set the title bar accordingly. I put the 1 second sleep in just to avoid any possible race conditions, but I'm not sure it's necessary. If you don't want to see all the command-line args, you can pre-process command any way you like.

My thanks to the folks on python-win32 mailing list, and Thomas Heller in particular, for helping with the 'set title' portion of this question.

https://en.xdnf.cn/q/69834.html

Related Q&A

Sending Godaddy email via Django using python

I have these settings EMAIL_HOST = smtpout.secureserver.net EMAIL_HOST_USER = [email protected] EMAIL_HOST_PASSWORD = password DEFAULT_FROM_EMAIL = [email protected] SERVER_EMAIL = [email protected] EM…

python math, numpy modules different results?

I get slightly different results calculating the cosine of a value. How can I check that this difference is within machine precision?import math math.cos(60.0/180.0*math.pi) -> 0.5000000000000001im…

How to extract equation from a polynomial fit?

My goal is to fit some data to a polynomial function and obtain the actual equation including the fitted parameter values. I adapted this example to my data and the outcome is as expected. Here is my c…

python dictionary conundrum

On the console I typed in>>> class S(str): pass ... >>> a = hello >>> b = S(hello) >>> d = {a:a, b:b} >>> d {hello: hello} >>> type(d[a]) <class…

Celery 4 not auto-discovering tasks

I have a Django 1.11 and Celery 4.1 project, and Ive configured it according to the setup docs. My celery_init.py looks likefrom __future__ import absolute_importimport osfrom celery import Celery# set…

Is it possible to use a custom filter function in pandas?

Can I use my helper function to determine if a shot was a three pointer as a filter function in Pandas? My actual function is much more complex, but i simplified it for this question.def isThree(x, y…

what is request in Django view

In the Django tutorial for the first app in Django we havefrom django.http import HttpResponsedef index(request):return HttpResponse("Hello, world. Youre at the polls index.")And then the url…

Cannot update python package on anaconda to latest version

Some of my python packages on anaconda cannot be updated to the latest version.For instance, beautifulsoup4 latest version on anaconda is v4.71 as seen in the release notes. https://docs.anaconda.com/a…

How does tensorflow.pad work?

There is the example of tensorflow.pad():# t = is [[1, 2, 3], [4, 5, 6]]. # paddings is [[1, 1,], [2, 2]]. # rank of t is 2.tf.pad(t, paddings, "CONSTANT") ==> [[0, 0, 0, 0, 0, 0, 0],[…

Installing PyPotrace on Windows 10

I would like to install Potrace on my Windows 10 Computer and I will be using it with python 2.7.5. I am following the installation instruction from this site.( https://pypi.python.org/pypi/pypotrace) …