Czy podczas uruchamiania skryptu Pythona w trybie bezczynności można przekazać argumenty linii poleceń (args)?

Testuję kod Pythona, który parsuje wejście wiersza poleceń. Czy jest sposób, aby przekazać to wejście przez IDLE? Obecnie zapisuję w edytorze bezczynności i uruchamiam z wiersza polecenia.

Uruchamiam Windows.

Author: HostileFork, 2010-01-27

9 answers

Nie wygląda na to, że IDLE zapewnia sposób, aby to zrobić poprzez GUI, ale możesz zrobić coś takiego:

idle.py -r scriptname.py arg1 arg2 arg3

Możesz również ustawić sys.argv ręcznie, jak:

try:
    __file__
except:
    sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2']

(kredyt http://wayneandlayne.com/2009/04/14/using-command-line-arguments-in-python-in-idle/)

 31
Author: danben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-27 17:37:14

/ Align = "center" bgcolor = "#e0ffe0 " / król Norwegii / / align = center / ...

2) możesz dodać linię testową przed głównym wywołaniem funkcji, która dostarcza tablicę argumentów (lub tworzy test jednostkowy, który wykonuje to samo), lub set sys./ align = "left" /

Na przykład...

sys.argv = ["wordcount.py", "--count", "small.txt"]
 10
Author: ackmondual,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-16 05:00:50

Oto kilka sposobów, które mogę wymyślić:

1) możesz wywołać funkcję "main" bezpośrednio na bezczynnej konsoli z argumentami, jeśli chcesz.

2) możesz dodać linię testową przed głównym wywołaniem funkcji, która dostarcza tablicę argumentów (lub utworzyć test jednostkowy, który robi to samo), lub ustawić sys./ align = "left" /

3) możesz uruchomić Pythona w trybie interaktywnym na konsoli i przekazać argumenty:

C:\> python.exe -i some.py arg1 arg2
 5
Author: Seth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-27 17:38:54

Ostatnia łatka , dla Issue 5680, powinna w końcu zacząć dopuszczać tę funkcjonalność w przyszłych wydaniach IDLE. W międzyczasie, jeśli chcesz, aby twój skrypt automatycznie wykrywał bezczynność i pytał o wartości argumentów linii poleceń , możesz wkleić (coś w tym stylu) to na początek kodu:

#! /usr/bin/env python3

import sys

def ok(x=None):
      sys.argv.extend(e.get().split())
      root.destroy()


if 'idlelib.rpc' in sys.modules:

      import tkinter as tk

      root = tk.Tk()
      tk.Label(root, text="Command-line Arguments:").pack()

      e = tk.Entry(root)
      e.pack(padx=5)

      tk.Button(root, text="OK", command=ok,
                default=tk.ACTIVE).pack(pady=5)

      root.bind("<Return>", ok)
      root.bind("<Escape>", lambda x: root.destroy())

      e.focus()
      root.wait_window()
Podążałbyś za tym swoim zwykłym kodem. ie. print(sys.argv)

Jeśli jest używany w Pythonie 2.6/2.7, pamiętaj, aby kapitalizować: import Tkinter as tk

na w tym przykładzie starałem się znaleźć szczęśliwą równowagę między funkcjami i zwięzłością. W razie potrzeby możesz dodawać lub usuwać funkcje!

Tutaj wpisz opis obrazka

Aktualizacja: 2018-03-31:

Żądanie pull jest nadal otwarte: (

 3
Author: veganaiZe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-01 08:32:29

Ten kod działa dla mnie świetnie, mogę użyć "F5" w trybie bezczynności, a następnie wywołać ponownie z interaktywnego monitu:

def mainf(*m_args):
    # Overrides argv when testing (interactive or below)
    if m_args:
        sys.argv = ["testing mainf"] + list(m_args)

...

if __name__ == "__main__":
    if False: # not testing?
        sys.exit(mainf())
    else:
        # Test/sample invocations (can test multiple in one run)
        mainf("--foo=bar1", "--option2=val2")
        mainf("--foo=bar2")
 1
Author: MarcH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-20 10:54:45

Visual Studio 2015 ma dodatek do Pythona. Możesz podać argumenty z tym. VS 2015 jest teraz wolny.

 1
Author: eddyq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-10 17:38:28

Na podstawie postu danben, oto moje rozwiązanie, które działa w bezczynności:

try:  
    sys.argv = ['fibo3_5.py', '30']  
    fibonacci(int(sys.argv[1]))  
except:  
    print(str('Then try some other way.'))  
 1
Author: user164969,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-11 23:12:20

Auto-detect IDLE and Prompt for Command-line Arguments

#! /usr/bin/env python3

import sys

# Prompt user for (optional) command line arguments, when run from IDLE:
if sys.modules['idlelib']: sys.argv.extend(input("Args: ").split())


Zmień "input" na "raw_input" dla Python2.

 1
Author: veganaiZe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-09 04:26:16

Odpowiedź z veganaiZe tworzy KeyError poza bezczynnością w Pythonie 3.6.3. Można to rozwiązać, zastępując if sys.modules['idlelib']: przez if 'idlelib' in sys.modules: Jak Poniżej.

import argparse
# Check if we are using IDLE
if 'idlelib' in sys.modules:
    # IDLE is present ==> we are in test mode
    print("""====== TEST MODE =======""")
    args = parser.parse_args([list of args])
else:
    # It's command line, this is production mode.
    args = parser.parse_args()
 0
Author: plep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-29 16:52:55