Is it possible to pass arguments to a python made exe at runtime?

前端 未结 4 810
终归单人心
终归单人心 2021-02-14 07:34

I\'m experimenting with file I/O. I have a small practice program that creates a text file when run. I packaged it with pyinstaller so that double clicking on the exe creates a

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 08:18

    Yes, you can do it with sys.argv. Check out this link: http://docs.python.org/library/sys.html#sys.argv. But remember not to forget import sys, and then you can use it. import sys

    # If there is an argument passed to your file
    if len(sys.argv) > 1:
        # argv[1] has your filename
        filename = sys.argv[1]
        print (filename)
    
    # Output...
    # new-host:~ yanwchan$ python3.2 test.py text.txt
    # text.txt
    

    argv[0] has test.py

    argv[1] has text.txt

    Edit: However, I do some more research on this topic and found out this: https://stackoverflow.com/a/4188500/1276534

    As katrielalex points out, maybe you can look into argparse as well.? It provides a lot more functionality as well as safety check. Interesting information.

    And here is a great tutorial: http://www.doughellmann.com/PyMOTW/argparse/

提交回复
热议问题