python -c 妙用
前言
python -c 命令还是有用的哈
正文
python的 -c 可以在命令行中调用 python 代码, 实际上 -c 就是 command 的意思
官方文档中解释为(节选自: python docs):
Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code.
If this option is given, the first element of
sys.argvwill be"-c"and the current directory will be added to the start ofsys.path(allowing modules in that directory to be imported as top level modules).Raises an auditing event
cpython.run_commandwith argumentcommand.
简单来说, 就是 python -c 可以在命令行中执行 python 代码, 跟把代码放置在 .py 文件中然后运行这个文件比无明显差别, 我们来测试一下
python -c "print('TTXT')"
随后正确输出了 TTXT
需要注意的是, python -c 后必须跟一个字符串, 因此必须带上引号, 而且在要执行的代码中也不要重叠, 这样会引发错误, 这是因为 python 认不出该到哪里结尾, 例如
python -c "print("TTXT")"
这样就会报错, 输出
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'TTXT' is not defined
我们一般可以使用三引号来标示需要执行的代码, 例如
python -c '''print("TTXT")'''
这样还有一个好处就是也可以执行多行的代码, 例如
python -c '''
import arrow
print(arrow.now())
'''
这样也是可以的, 也可以定义并调用函数
python -c '''
def a():
print(111)
a()
'''
当然也是可以导入自定义的模块或者已经安装的包的
妙用
那么 -c 有什么妙用呢? 这个要具体问题具体分析, 比如说我在开发中要使用一个第三方包 patool, 项目在 github, 这个包作用是根据格式解压压缩文件, 但是在调用时发生总是会报找不到 patoollib 模块的错误
官方给的例子如下
import patoolib
patoolib.extract_archive("archive.zip", outdir="/tmp")
排查发现, 该模块的起始文件最上面写定了python的地址, 导致运行时强制指定了python路径而没有使用自己的虚拟环境, 因为 /usr/bin/python 没有安装 patool 包所以报错找不到
py文件节选
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2015 Bastian Kleineidam
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
patool [global-options] {extract|list|create|diff|search|formats} [sub-command-options] <command-args>
"""
def main():
"""Parse options and execute commands."""
try:
argparser = create_argparser()
args = argparser.parse_args()
if args.command is None:
# Python 3.3.1 under linux allows an empty command somehow
argparser.error("too few arguments")
# run subcommand function
res = globals()["run_%s" % args.command](args)
except KeyboardInterrupt:
log_error("aborted")
res = 1
except Exception:
log_internal_error()
res = 2
return res
if __name__ == '__main__':
sys.exit(main())
似乎只能将包的源代码修改, 实际上只要把第一行删除即可, 但是考虑到Docker部署, 就没有更好的办法了吗? 使用 python -c 即可完美解决
我们使用 python -c 在命令行中使用我们指定的 python 去执行模块, 就会使py文件中指定的不生效, 所以调用改成如下即可
code = f"import patoolib; patoolib.extract_archive('{file}', outdir='{unfile}')"
proc = await asyncio.create_subprocess_exec(sys.executable, '-c', code)
await proc.wait()
这样就可以完美的解决问题了, 不用修改原来包的代码
python -c 妙用的更多相关文章
- 「Python实用秘技05」在Python中妙用短路机制
本文完整示例代码及文件已上传至我的Github仓库https://github.com/CNFeffery/PythonPracticalSkills 这是我的系列文章「Python实用秘技」的第5期 ...
- python with妙用
class aa(): def bb(self): print("hhhh") return "hello world" def __enter__(self) ...
- python魔法函数__dict__和__getattr__的妙用
python魔法函数__dict__和__getattr__的妙用 __dict__ __dict__是用来存储对象属性的一个字典,其键为属性名,值为属性的值. 既然__dict__是个字典那么我们就 ...
- LD_PRELOAD的妙用,让python支持自己编译的Sqlite
LD_PRELOAD的妙用,让python支持自己编译的Sqlite LD_PRELOAD=/usr/local/sqlite/lib/libsqlite3.so.0 python3 -c " ...
- Python:eval的妙用和滥用
时间 2014-07-08 13:05:24 CSDN博客 原文 http://blog.csdn.net/zhanh1218/article/details/37562167 主题 Python ...
- python的locals()妙用
如果你是个喜欢偷懒的程序员并想让代码看起来更加简明,可以利用 Python 的内建函数 locals() .它返回的字典对所有局部变量的名称与值进行映射.因此,前面的视图可以重写成下面这个样子:def ...
- 使用Python的requests库进行接口测试——session对象的妙用
from:http://blog.csdn.net/liuchunming033/article/details/48131051 在进行接口测试的时候,我们会调用多个接口发出多个请求,在这些请求中有 ...
- Python 妙用heapq
小顶堆求TopK大 大顶堆求BtmK小 题外话 Python有一个内置的模块,heapq标准的封装了最小堆的算法实现.下面看两个不错的应用. 小顶堆(求TopK大) 话说需求是这样的: 定长的序列,求 ...
- Python eval 函数妙用
eval 功能:将字符串str当成有效的表达式来求值并返回计算结果. 语法: eval(source, globals, locals) -> value 参数: source:一个Python ...
随机推荐
- 题解-洛谷P4229 某位歌姬的故事
题面 洛谷P4229 某位歌姬的故事 \(T\) 组测试数据.有 \(n\) 个音节,每个音节 \(h_i\in[1,A]\),还有 \(m\) 个限制 \((l_i,r_i,g_i)\) 表示 \( ...
- CSP-S2020 DP专项训练
前言 \(\text{CPS-S2020}\) 已然临近,而 \(\text{DP}\) 作为联赛中的常考内容,是必不可少的复习要点,现根据教练和个人刷题,整理部分好题如下(其实基本上是直接搬--). ...
- 算法——和为K的连续子数组
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数. 输入:nums = [1,1,1], k = 2 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况. 链 ...
- sqli-labs less-24(二次注入)
less-24 原理: 在网站处理用户提交的数据的时候,只是将某些敏感字符进行了转义.因而使得用户第一次提交的时候不会被当做代码执行.但是这些数据存入数据库的时候却没有转义,而网站程序默认数据库中的数 ...
- 程序员必读的 99 本书籍 & 资源
作为程序员,始终要保持学习,一直带着纸质书还是很不便的,因此电子书对于我们还是挺需要的.为了方便广大的小伙伴也能方便找到对应的电子书,我花费洪荒之力从各个搜索网站收集了几百本常用的电子书,找到了,我要 ...
- 你来说一下springboot的启动时的一个自动装配过程吧
前言 继续总结吧,没有面试就继续夯实自己的基础,前阵子的在面试过程中遇到的各种问题陆陆续续都会总结出来分享给大家,这次要说的也是面试中被问到的一个高频的问题,我当时其实没答好,因为很早之前是看到spr ...
- I/O方式(本章最重要)
目录 程序查询方式 程序查询方式接口结构 例题 本节回顾 程序中断方式 中断的基本概念 工作流程 中断请求 分类 中断请求标记 中断响应 判优实现 优先级设置 中断处理过程 中断隐指令 硬件向量法 中 ...
- vue 按键修饰符 keyup
按键修饰符 keyup 通过官方文档可查询到特殊的按键修饰符 .enter .tab .delete (捕获"删除"和"退格"键) .esc .space .u ...
- SpringBoot从入门到精通教程(五)
上节,我们讲了 SpringBoot 如何使用MyBatis 今天我们讲讲 Springboot Logo自定义的问题, 我们在启动 SpringBoot 时,控制台会打印 SpringBoot Lo ...
- Python 中的运算符重载
本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理 一种运算符对于不同类型的对象,有不同的使用方式.例如, + 用于整型对象,表示两个数相加:用于字符串 ...