When running a python script in IDLE, is there a w

2019-01-16 14:01发布

I'm testing some python code that parses command line input. Is there a way to pass this input in through IDLE? Currently I'm saving in the IDLE editor and running from a command prompt.

I'm running Windows.

10条回答
仙女界的扛把子
2楼-- · 2019-01-16 14:32

Answer from veganaiZe produces a KeyError outside IDLE with python 3.6.3. This can be solved by replacing if sys.modules['idlelib']: by if 'idlelib' in sys.modules: as below.

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()
查看更多
Rolldiameter
3楼-- · 2019-01-16 14:34

In a pinch, Seth's #2 worked....

2) You can add a test line in front of your main function call which supplies an array of arguments (or create a unit test which does the same thing), or set sys.argv directly.

For example...

sys.argv = ["wordcount.py", "--count", "small.txt"]
查看更多
做个烂人
4楼-- · 2019-01-16 14:39

import sys

sys.argv = [sys.argv[0], '-arg1', 'val1', '-arg2', 'val2']

//If you're passing command line for 'help' or 'verbose' you can say as:

sys.argv = [sys.argv[0], '-h']

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-16 14:43

This code works great for me, I can use "F5" in IDLE and then call again from the interactive prompt:

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")
查看更多
你好瞎i
6楼-- · 2019-01-16 14:44

Here are a couple of ways that I can think of:

1) You can call your "main" function directly on the IDLE console with arguments if you want.

2) You can add a test line in front of your main function call which supplies an array of arguments (or create a unit test which does the same thing), or set sys.argv directly.

3) You can run python in interactive mode on the console and pass in arguments:

C:\> python.exe -i some.py arg1 arg2
查看更多
Summer. ? 凉城
7楼-- · 2019-01-16 14:49

Based on the post by danben, here is my solution that works in IDLE:

try:  
    sys.argv = ['fibo3_5.py', '30']  
    fibonacci(int(sys.argv[1]))  
except:  
    print(str('Then try some other way.'))  
查看更多
登录 后发表回答