Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ways to execute Python code on the terminal

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the ways to execute Python code in the terminal". In daily operation, I believe many people have doubts about what are the ways to execute Python code in the terminal. Xiaobian consulted various materials and sorted out simple and easy operation methods. I hope to help you answer the doubts about "what are the ways to execute Python code in the terminal"! Next, please follow the small series to learn together!

1. Through standard inputs and pipes

Because how to pipe something to a process is a shell matter, I'm not going to go into detail. There is no doubt that you can pass code into Python.

#pipe content to python echo "print ('hi ')"| python

If you redirect files to Python, this obviously works too.

#redirect a file to python python

Thanks to Python's UNIX heritage, none of this is too surprising.

2. String specified by-c

If you just need to check something quickly, you can pass the code as a string on the command line.

#use python's-c argument python -c "print ('hi ')"

I personally use it when I need to examine just one or two lines of code, rather than launching REPL(i.e., interactive interpreter, for example, typing python into the Windows console). C parameter usage can eliminate the process of entering the interpreter interface)

3. Path to file

The most well-known method of passing code to python is probably via file paths.

#Specify python file path python spam.py

The key to doing this is to place the directory containing the file in sys. path. This way all your imports can continue to be used. But that's why you can't/shouldn't pass in module paths contained in a package. Because sys.path may not contain the directory for the package, all imports will be relative to a different directory than what you expect for the package.

4. Use-m for packages

The correct way to execute Python packages is to use-m and specify the package name to run.

python -m spam

It uses runpy[5] at the bottom. To do this in your project, simply specify a__main__.py file in the package, which will be executed as__main__. And submodules can be imported just like any other module, so you can test them in a variety of ways.

I know some people like to write a main submodule in a package and then write it__main__.py as:

from . import main if __name__ == "__main__": main.main()

Personally, I am not interested in a separate main module, but rather put all the relevant code directly into__main__.py, because I feel that these module names are redundant.

The author doesn't care about the "main" or "__main__" modules as entry files because they can be executed using only their package names. I think this also implies that entry modules should no longer be imported by other modules. My last article [6] was more radical than the author's view, arguing that even that if statement should not be written.)

5. Contents

The definition__main__.py can also be extended to directories. If you look at the example that led to this blog post, python news is executable because the news directory has a__main__.py file. This directory is executed by Python like a file path.

Now you might ask,"Why not just specify the file path?" "Well, frankly, there's one thing to be clear about file paths. During the release process, I could simply write instructions to run python news/announce.py, but there is no exact reason why this mechanism exists.

Plus I can change file names later and no one will notice. Plus I know the code comes with auxiliary files, so it makes sense to put it in a directory rather than as a single file.

Of course, I could have made it a package using-m, but that's not necessary, because the announce script is simple and I know it needs to be kept as a separate self-contained file (less than 200 lines, and the test module is about the same length).

Moreover, the__main__.py file is very simple.

import runpy # Change 'announce' to whatever module you want to run. runpy.run_module('announce', run_name='__main__', alter_sys=True)

Now obviously you have to deal with dependencies, but if your script uses only the standard library or places dependent modules next to__main__.py, then that's enough!

(I think the author is a bit "showy" here, because this kind of writing requires knowing the usage of runpy, but just like the previous one, running a package with-m parameter uses runpy at the bottom.) However, the benefits of showmanship are also very obvious, that is,__main__.py does not need to import the announce module, or it is executed as the main module, and the original dependency import relationship will not be destroyed.)

Execute a compressed file

If you do have multiple files and/or dependent modules, and you want to distribute all your code as a unit, you can place it in a compressed file with a__main__.py, and put the compressed file in sys.path, Python will run the__main__.py file for you.

#Pass a zip to Python app.pyz

People are now accustomed to naming such compressed files with the.pyz file extension, but this is purely traditional and doesn't affect anything; you can of course use the.zip file extension.

To simplify the creation of such executable zip files, the standard library provides the zipapp[7] module. It generates__main__.py for you and adds a shebang line, so you don't even need to specify python if you don't want to specify it on UNIX. If you want to move a bunch of pure Python code, this is a good way to do it.

Unfortunately, compressed files can only be run this way if all the code they contain is pure Python. Executing compressed files is not valid for extension modules (this is why setuptools has a zip_safe[8] flag). extension module (non-Python file such as C/C++)

To load an extension module, Python must call the dlopen()[9] function, which passes in a file path, but this obviously doesn't work when the file path is already contained within the compressed file.

I know of at least one person who spoke to the glibc team about supporting passing memory buffers into compressed files so Python could read extension modules into memory and pass them to compressed files, but the glibc team disagreed if memory served that purpose.

But not all hope is lost! You can use projects like shiv[10] that bundle your code and then provide a__main__.py to handle extracting, caching, and executing code for you. Although not as ideal as a pure Python solution, it does work, and in this case is elegant.

At this point, the study of "what are the ways to execute Python code in the terminal" is over, hoping to solve everyone's doubts. Theory and practice can better match to help you learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report