How to determine if Python script was run via comm

2019-02-11 12:53发布

Background

I would like my Python script to pause before exiting using something similar to:

raw_input("Press enter to close.")

but only if it is NOT run via command line. Command line programs shouldn't behave this way.

Question

Is there a way to determine if my Python script was invoked from the command line:

$ python myscript.py

verses double-clicking myscript.py to open it with the default interpreter in the OS?

10条回答
Deceive 欺骗
2楼-- · 2019-02-11 13:51

From the idea behind this answer, adding for Win10 compatibility (Ripped from Python 2.7 script; modify as needed):

import os, psutil
status = 1
if __name__ =="__main__":
    status = MainFunc(args)
    args = sys.argv
    running_windowed = False
    running_from = psutil.Process(os.getpid()).parent().name()
    if running_from == 'explorer.exe':
        args.append([DEFAULT OR DOUBLE CLICK ARGS HERE])
        running_windowed = True
    if running_windowed:
        print('Completed. Exit status of {}'.format(status))
        ready = raw_input('Press Enter To Close')
    sys.exit(status)

There is a number of switch like statements you could add to be more universal or handle different defaults.

查看更多
姐就是有狂的资本
3楼-- · 2019-02-11 13:52

I also had that question and, for me, the best solution is to set an environment variable in my IDE (PyCharm) and check if that variable exists to know if the script is being executed either via the command line or via the IDE.

To set an environment variable in PyCharm check: How to set environment variables in PyCharm?

Example code (environment variable: RUNNING_PYCHARM = True):

import os

# The script is being executed via the command line
if not("RUNNING_PYCHARM" in os.environ):
    raw_input("Press enter to close.")

I hope it works for you.

查看更多
小情绪 Triste *
4楼-- · 2019-02-11 13:54

I believe this CAN be done. At least, here is how I got it working in Python 2.7 under Ubuntu 14.04:

#!/usr/bin/env python
import os, psutil

# do stuff here

if psutil.Process(os.getpid()).parent.name == 'gnome-terminal':
    raw_input("Press enter to close...")

Note that -- in Ubuntu 14 with the Gnome desktop (aka Nautilus) -- you might need to do this:

  • from a Nautilus window (the file browser), select Edit(menu)->Preferences(item) then Behavior(tab)->Executable Text Files(section)->Ask Each Time(radio).
  • chmod your script to be executable, or -- from a Nautilus window (the file browser) -- right click on the file->Properties(item) then Permissions(tab)->Execute:Allow executing file as program(checkbox)
  • double-click your file. If you select "Run in Terminal", you should see the "Type enter to close..." prompt.
  • now try from a bash prompt; you should NOT see the prompt.

To see how this works, you can fiddle with this (based on the answer by from @EduardoIvanec):

#!/usr/bin/env python
import os
import sys
import psutil

def parent_list(proc=None, indent=0):
    if not proc:
        proc = psutil.Process(os.getpid())
    pid = proc.pid
    name = proc.name
    pad = " " * indent
    s = "{0}{1:5d} {2:s}".format(pad, pid, name)
    parent = proc.parent
    if parent:
        s += "\n" + parent_list(parent, indent+1)
    return s

def invoked_from_bash_cmdline():
    return psutil.Process(os.getpid()).parent.name == "bash"

def invoked_as_run_in_terminal():
    return psutil.Process(os.getpid()).parent.name == "gnome-terminal"

def invoked_as_run():
    return psutil.Process(os.getpid()).parent.name == "init"


if sys.stdin.isatty():
    print "running interactively"
    print parent_list()
    if invoked_as_run_in_terminal():
        raw_input("Type enter to close...")

else:
    with open('output','w') as f:
        f.write("running in the background!\n")
        f.write("parent list:\n")
        f.write(parent_list())
查看更多
Root(大扎)
5楼-- · 2019-02-11 13:56

Although this isn't a very good solution, it does work (in windows at least).

You could create a batch file with the following contents:

@echo off
for %%x in (%cmdcmdline%) do if /i "%%~x"=="/c" set DOUBLECLICKED=1
start <location of python script>
if defined DOUBLECLICKED pause

If you want to be able to do this with a single file, you could try the following:

@echo off
setlocal EnableDelayedExpansion
set LF=^


::  The 2 empty lines are necessary
for %%x in (%cmdcmdline%) do if /i "%%~x"=="/c" set DOUBLECLICKED=1
echo print("first line of python script") %LF% print("second and so on") > %temp%/pyscript.py
start /wait console_title pyscript.py
del %temp%/pyscript.py
if defined DOUBLECLICKED pause

Batch code from: Pausing a batch file when double-clicked but not when run from a console window? Multi-line in batch from: DOS: Working with multi-line strings

查看更多
登录 后发表回答