简体   繁体   中英

How can I determine who is calling my Python script?

I am writing a Python script, and I'd like its behaviour to depend on who's calling that script:

  • if it is called from within a batchfile, I want the Python script to write its output to a logfile.
  • if it is called manually from a command prompt, I want the Python script to write its output on screen.

My batchfile looks as follows:

  python py_script.py

Is there any way to get this done? I had a look at os.environ.has_key() but I don't know how to use this.

Just pass an argument to your script to tell him where to write... command line arguments are passed in sys.argv . There are a couple packages in the stdlib to deal with them but you might not have need for here that's the only option for your script.

The easiest way to do this is (as tobias_k remarks in the comments) merely to pipe to a log file when called from a script

REM This is your batch file
python py_script.py >> your_log_file.txt

Bruno's suggestion in the other answer to pull a flag from sys.argv is certainly valid, but you're going to end up doing a lot of duplicate code. Your codebase will then look like:

if LOGGING:
    with open(PATH_TO_LOGFILE, 'a') as logf:
        logf.write(some_txt)
else:
    print(some_txt)

anytime you have a print call. Alternatively you could do some INCREDIBLY ugly stuff like

if __name__ == "__main__":
    if LOGGING:
        old_stdout = sys.sdout
        with open(PATH_TO_LOGFILE, 'a') as logf:
            sys.stdout = logf
            main()
        sys.stdout = old_stdout

Honestly that's ugly and hackish ( and might not even work, I've never tried to reassign sys.stdout ). Just use shell redirection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM