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 new folder and places a text file with “hello world” inside of it. Easy peasy.
Then I started wondering about main(). This is just a function like any other, right? So does that mean I can pass arguments to it at runtime?
I was thinking about the Steam client and how you can put stuff like ‘-dev’ and ‘-console’ in the shortcut. Is there a way to do this to a python exe that I have made?
I may be explaining terribly, so here’s an example:
def makeFile(string):
if string:
f = open('mytext.txt', 'w') #create text file in local dir
print >> f, 'hello, ' + string + '! \nHow are ya?'
f.close()
else:
f = open('mytext.txt', 'w') #create text file in local dir
print >> f, 'hello, person! \nHow are ya?'
f.close()
def main(string = None):
makeFile(string)
So if I take this code and make it an exe, would I be able to add my optional arguments somehow.
I tried the above code, and the running test.exe --"myname" but that didn’t work.
Is there a way to do this?
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 forgetimport sys, and then you can use it.import sys
argv[0]hastest.pyargv[1]hastext.txtEdit: 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
argparseas 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/