To make this work with your project all you need to do is specify a _main_.py inside your package and it will get executed as _main_. The proper way to execute a package is by using -m and specifying the package you want to run. Since sys.path won't have the directory that contains the package, all your imports will be relative to a different directory than you expect for your package. But this is also why you can't/shouldn't pass in the path to a module that's contained from within a package. This is so that all of your imports continue to work. The key thing to realize about this is the directory containing the file is put at the front of sys.path. python spam.py Specifying a file path for python Probably the most well-known way to pass code to python is via a file path. I personally use this when I need to check something that's only a line or two of code instead of launching the REPL. python -c "print('hi')" Using the -c flag with python If you just need to quickly check something, passing the code in as a string on the command-line works. Nothing really surprising here thanks to Python's UNIX heritage. python < spam.py Redirecting a file into python This obviously also works if you redirect a file into Python. echo "print('hi')" | python Piping text into python Needless to say, you can pipe code into Python. Since how you pipe things into a process is shell-specific, I'm not going to dive too deep into this. A co-worker the other day asked how that worked since everyone on my team knows to use -m (see my post on using -m with pip as to why)? That made me realize that other people probably don't know the myriad of ways you can point python at code to execute, hence this blog post. As part of our release process we have a step where you are supposed to run python news which points Python at the news directory in our repository. For the Python extension for VS Code, I wrote a simple script for generating our changelog (think Towncrier, but simpler, Markdown-specific, and tailored to our needs).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |