标签归档:command-line

在Python中获取命令行密码输入

问题:在Python中获取命令行密码输入

您知道在Linux中尝试一些Sudo东西时如何告诉您输入密码,并且在键入时,终端窗口中什么都没有显示(密码未显示)?

有没有办法在Python中做到这一点?我正在编写一个脚本,该脚本需要非常敏感的信息,并希望在键入时将其隐藏。

换句话说,我想从用户那里获取密码而不显示密码。

You know how in Linux when you try some Sudo stuff it tells you to enter the password and, as you type, nothing is shown in the terminal window (the password is not shown)?

Is there a way to do that in Python? I’m working on a script that requires so sensitive info and would like for it to be hidden when I’m typing it.

In other words, I want to get the password from the user without showing the password.


回答 0

使用getpass.getpass()

from getpass import getpass
password = getpass()

可以将可选提示作为参数传递;默认值为"Password: "

请注意,此功能需要正确的终端,因此它可以关闭键入字符的回显– 有关更多详细信息,请从IDLE运行时,请参见“ GetPassWarning:无法控制终端上的回显”

Use getpass.getpass():

from getpass import getpass
password = getpass()

An optional prompt can be passed as parameter; the default is "Password: ".

Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.


回答 1

import getpass

pswd = getpass.getpass('Password:')

getpass可在Linux,Windows和Mac上使用。

import getpass

pswd = getpass.getpass('Password:')

getpass works on Linux, Windows, and Mac.


回答 2

为此使用getpass

getpass.getpass-提示用户输入密码而不回显

Use getpass for this purpose.

getpass.getpass – Prompt the user for a password without echoing


回答 3

此代码将打印一个星号,而不是每个字母。

import sys
import msvcrt

passwor = ''
while True:
    x = msvcrt.getch()
    if x == '\r':
        break
    sys.stdout.write('*')
    passwor +=x

print '\n'+passwor

This code will print an asterisk instead of every letter.

import sys
import msvcrt

passwor = ''
while True:
    x = msvcrt.getch()
    if x == '\r':
        break
    sys.stdout.write('*')
    passwor +=x

print '\n'+passwor

回答 4

15.7。getpass —便携式密码输入

#!/usr/bin/python3
from getpass import getpass
passwd = getpass("password: ")
print(passwd)

你可以在这里阅读更多

15.7. getpass — Portable password input

#!/usr/bin/python3
from getpass import getpass
passwd = getpass("password: ")
print(passwd)

You can read more here


回答 5

更新@Ahmed ALaa的答案

# import msvcrt
import getch

def getPass():
    passwor = ''
    while True:
        x = getch.getch()
        # x = msvcrt.getch().decode("utf-8")
        if x == '\r' or x == '\n':
            break
        print('*', end='', flush=True)
        passwor +=x
    return passwor

print("\nout=", getPass())

msvcrt仅适用于Windows,但从PyPI获取getch应该对两者都适用(我仅在linux上进行过测试)。您也可以注释/取消注释这两行,以使其适用于Windows。

Updating on the answer of @Ahmed ALaa

# import msvcrt
import getch

def getPass():
    passwor = ''
    while True:
        x = getch.getch()
        # x = msvcrt.getch().decode("utf-8")
        if x == '\r' or x == '\n':
            break
        print('*', end='', flush=True)
        passwor +=x
    return passwor

print("\nout=", getPass())

msvcrt us only for windows, but getch from PyPI should work for both (I only tested with linux). You can also comment/uncomment the two lines to make it work for windows.


如何找到我的系统中安装了哪个版本的TensorFlow?

问题:如何找到我的系统中安装了哪个版本的TensorFlow?

我需要找到已安装的TensorFlow版本。我正在使用Ubuntu 16.04长期支持。

I need to find which version of TensorFlow I have installed. I’m using Ubuntu 16.04 Long Term Support.


回答 0

这取决于您安装TensorFlow的方式。我将使用TensorFlow的安装说明所用的相同标题来组织此答案。


点安装

跑:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

请注意,在某些Linux发行版中,它python是符号链接的/usr/bin/python3,因此在这些情况下,请使用python代替python3

pip list | grep tensorflow适用于Python 2或pip3 list | grep tensorflow适用于Python 3的版本还将显示已安装的Tensorflow的版本。


Virtualenv安装

跑:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for both Python 2 and Python 3

pip list | grep tensorflow 还将显示已安装的Tensorflow的版本。

例如,我已经在virtualenvPython 3的a中安装了TensorFlow 0.9.0 。因此,我得到:

$ python -c 'import tensorflow as tf; print(tf.__version__)'
0.9.0

$ pip list | grep tensorflow
tensorflow (0.9.0)

This depends on how you installed TensorFlow. I am going to use the same headings used by TensorFlow’s installation instructions to structure this answer.


Pip installation

Run:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

Note that python is symlinked to /usr/bin/python3 in some Linux distributions, so use python instead of python3 in these cases.

pip list | grep tensorflow for Python 2 or pip3 list | grep tensorflow for Python 3 will also show the version of Tensorflow installed.


Virtualenv installation

Run:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for both Python 2 and Python 3

pip list | grep tensorflow will also show the version of Tensorflow installed.

For example, I have installed TensorFlow 0.9.0 in a virtualenv for Python 3. So, I get:

$ python -c 'import tensorflow as tf; print(tf.__version__)'
0.9.0

$ pip list | grep tensorflow
tensorflow (0.9.0)

回答 1

python中几乎每个普通软件包都将变量.__version__或分配VERSION给当前版本。因此,如果要查找某些软件包的版本,可以执行以下操作

import a
a.__version__ # or a.VERSION

对于张量流它将是

import tensorflow as tf
tf.VERSION

对于旧版本的tensorflow(低于0.10),请使用 tf.__version__

顺便说一句,如果您打算安装TF,请使用conda而不是pip进行安装

Almost every normal package in python assigns the variable .__version__ to the current version. So if you want to find the version of some package you can do the following

import a
a.__version__

For tensorflow it will be

import tensorflow as tf
tf.version.VERSION

For old versions of tensorflow (below 0.10), use tf.__version__


回答 2

如果您是通过pip安装的,则只需运行以下命令

$ pip show tensorflow
Name: tensorflow
Version: 1.5.0
Summary: TensorFlow helps the tensors flow

If you have installed via pip, just run the following

$ pip show tensorflow
Name: tensorflow
Version: 1.5.0
Summary: TensorFlow helps the tensors flow

回答 3

import tensorflow as tf

print(tf.VERSION)
import tensorflow as tf

print(tf.VERSION)

回答 4

如果您使用的是Python的anaconda发行版,

$ conda list | grep tensorflow
tensorflow    1.0.0       py35_0    conda-forge

使用Jupyter Notebook(IPython Notebook)进行检查

In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'

If you’re using anaconda distribution of Python,

$ conda list | grep tensorflow
tensorflow    1.0.0       py35_0    conda-forge

To check it using Jupyter Notebook (IPython Notebook)

In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'

回答 5

对于python 3.6.2:

import tensorflow as tf

print(tf.version.VERSION)

For python 3.6.2:

import tensorflow as tf

print(tf.version.VERSION)

回答 6

我从源代码安装了Tensorflow 0.12rc,以下命令为我提供了版本信息:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

下图显示了输出:

I installed the Tensorflow 0.12rc from source, and the following command gives me the version info:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

The following figure shows the output:


回答 7

在最新的TensorFlow版本1.14.0上

tf.VERSION

已弃用,而不是此用法

tf.version.VERSION

错误:

WARNING: Logging before flag parsing goes to stderr.
The name tf.VERSION is deprecated. Please use tf.version.VERSION instead.

On Latest TensorFlow release 1.14.0

tf.VERSION

is deprecated, instead of this use

tf.version.VERSION

ERROR:

WARNING: Logging before flag parsing goes to stderr.
The name tf.VERSION is deprecated. Please use tf.version.VERSION instead.

回答 8

要获取有关tensorflow及其选项的更多信息,可以使用以下命令:

>> import tensorflow as tf
>> help(tf)

To get more information about tensorflow and its options you can use below command:

>> import tensorflow as tf
>> help(tf)

回答 9

轻松获得KERAS和TENSORFLOW版本号->在终端中运行以下命令:

[用户名@usrnm:〜] python3

>>import keras; print(keras.__version__)

Using TensorFlow backend.

2.2.4

>>import tensorflow as tf; print(tf.__version__)

1.12.0

Easily get KERAS and TENSORFLOW version number –> Run this command in terminal:

[username@usrnm:~] python3

>>import keras; print(keras.__version__)

Using TensorFlow backend.

2.2.4

>>import tensorflow as tf; print(tf.__version__)

1.12.0


回答 10

tensorflow版本可以在终端或控制台上检查,也可以在任何IDE编辑器中检查(例如Spyder或Jupyter笔记本等)

简单命令检查版本:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)

>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'

The tensorflow version can be checked either on terminal or console or in any IDE editer as well (like Spyder or Jupyter notebook, etc)

Simple command to check version:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)

>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'

回答 11

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

-c表示以字符串形式传入的程序(终止选项列表)

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

Here -c represents program passed in as string (terminates option list)


回答 12

Jupyter Notebook中的Tensorflow版本:-

!pip list | grep tensorflow

Tensorflow version in Jupyter Notebook:-

!pip list | grep tensorflow

回答 13

如果您具有TensorFlow 2.x:

sess = tf.compat.v1.Session(config = tf.compat.v1.ConfigProto(log_device_placement = True))

If you have TensorFlow 2.x:

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))


回答 14

我猜是另一种变化:P

python3 -c 'print(__import__("tensorflow").__version__)'

Another variation, i guess :P

python3 -c 'print(__import__("tensorflow").__version__)'


为什么要使用argparse而不是optparse?

问题:为什么要使用argparse而不是optparse?

我注意到Python 2.7文档还包含另一个命令行解析模块。除了getoptoptparse我们现在有argparse

为什么还要创建另一个命令行解析模块?为什么要使用它代替optparse?我应该了解一些新功能吗?

I noticed that the Python 2.7 documentation includes yet another command-line parsing module. In addition to getopt and optparse we now have argparse.

Why has yet another command-line parsing module been created? Why should I use it instead of optparse? Are there new features that I should know about?


回答 0

从python开始2.7optparse已弃用,希望将来会消失。

argparse由于其原始页面(https://code.google.com/archive/p/argparse/)上列出的所有原因而更好:

  • 处理位置参数
  • 支持子命令
  • 允许其他可选前缀,例如+/
  • 处理零个或多个和一个或多个样式参数
  • 产生更多有用的使用信息
  • 为自定义类型和操作提供更简单的界面

PEP 389中也提供了更多信息,它是将argparse其纳入标准库的工具。

As of python 2.7, optparse is deprecated, and will hopefully go away in the future.

argparse is better for all the reasons listed on its original page (https://code.google.com/archive/p/argparse/):

  • handling positional arguments
  • supporting sub-commands
  • allowing alternative option prefixes like + and /
  • handling zero-or-more and one-or-more style arguments
  • producing more informative usage messages
  • providing a much simpler interface for custom types and actions

More information is also in PEP 389, which is the vehicle by which argparse made it into the standard library.


回答 1

为什么要使用它代替optparse?是我应该知道的新功能吗?

我认为,@ Nicholas的答案可以很好地解决这一问题,但您不能从以下的“元”问题开始:

为什么还要创建另一个命令行解析模块?

将任何有用的模块添加到标准库中时,这就是两难的境地:当出现一种提供更好的,但向后不兼容的,提供相同功能的方法时,您该怎么办?

您要么坚持旧的,公认的超越方式(通常在谈论复杂的软件包时:异步,扭曲,tkinter,wx或Qt等),要么最终以多种不兼容的方式完成同一件事(XML与命令行解析器相比,恕我直言的解析器是一个更好的例子-但email与处理类似问题的无数旧方法相比,程序包和它们之间的距离也不远;-)。

您可能会在文档中对过时的“过时”方式进行抱怨,但是(只要需要保持向后兼容性)就不能真正消除它们,而必须停止大型的重要应用程序迁移到较新的Python版本。

(第二个难题,与您的问题没有直接关系,总结成一句老话:“标准库是好的软件包将要消亡的地方……”每年约有一半的版本发布,但不是非常好的软件包,非常稳定,不需要经常发布的版本,实际上可能会因为在标准库中被“冻结”而遭受严重损失……但这确实是一个不同的问题)。

Why should I use it instead of optparse? Are their new features I should know about?

@Nicholas’s answer covers this well, I think, but not the more “meta” question you start with:

Why has yet another command-line parsing module been created?

That’s the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?

Either you stick with the old and admittedly surpassed way (typically when we’re talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, …) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers — but the email package vs the myriad old ways to deal with similar issues isn’t too far away either;-).

You may make threatening grumbles in the docs about the old ways being “deprecated”, but (as long as you need to keep backwards compatibility) you can’t really take them away without stopping large, important applications from moving to newer Python releases.

(Dilemma number two, not directly related to your question, is summarized in the old saying “the standard library is where good packages go to die”… with releases every year and a half or so, packages that aren’t very, very stable, not needing releases any more often than that, can actually suffer substantially by being “frozen” in the standard library… but, that’s really a different issue).


回答 2

添加Python原理的最佳来源是其PEP: PEP 389:argparse-新的命令行解析模块,尤其是标题为“ 为什么getopt和optparse不够?”的部分。

The best source for rationale for a Python addition would be its PEP: PEP 389: argparse – New Command Line Parsing Module, in particular, the section entitled, Why aren’t getopt and optparse enough?


回答 3

街上也有新孩子!

  • 除了已经提到的过时的optparse。[不使用]
  • argparse还提到了,这是不愿意包含外部库的人们的解决方案。
  • docopt是值得研究的外部库,它使用文档字符串作为输入的解析器。
  • click也是外部库,并使用修饰符定义参数。(我的来源建议:为什么单击
  • python-inquirer用于选择工具,基于Inquirer.js(repo

如果你需要一个更深入的比较,请阅读,你可能最终使用docopt点击。感谢Kyle Purdon!

There are also new kids on the block!

  • Besides the already mentioned deprecated optparse. [DO NOT USE]
  • argparse was also mentioned, which is a solution for people not willing to include external libs.
  • docopt is an external lib worth looking at, which uses a documentation string as the parser for your input.
  • click is also external lib and uses decorators for defining arguments. (My source recommends: Why Click)
  • python-inquirer For selection focused tools and based on Inquirer.js (repo)

If you need a more in-depth comparison please read this and you may end up using docopt or click. Thanks to Kyle Purdon!


回答 4

起初,我像@fmark一样不愿意从optparse切换到argparse,因为:

  1. 我以为差异不是很大。
  2. 默认情况下,相当多的VPS仍提供Python 2.6。

然后我看到了这个文档,argparse胜过optparse,尤其是在谈论生成有意义的帮助消息时: http //argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

然后我看到@Nicholas的“ argparse vs. optparse ”,说我们可以在python <2.7中使用argparse(是的,我以前不知道。)

现在,我的两个问题得到了很好的解决。我写这个希望是希望它可以帮助具有类似心态的其他人。

At first I was as reluctant as @fmark to switch from optparse to argparse, because:

  1. I thought the difference was not that huge.
  2. Quite some VPS still provides Python 2.6 by default.

Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

And then I saw “argparse vs. optparse” by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn’t know that before.)

Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.


从命令行运行功能

问题:从命令行运行功能

我有以下代码:

def hello():
    return 'Hi :)'

我将如何直接从命令行运行它?

I have this code:

def hello():
    return 'Hi :)'

How would I run this directly from the command line?


回答 0

使用-c (command)参数(假设您的文件名为foo.py):

$ python -c 'import foo; print foo.hello()'

或者,如果您不关心命名空间污染,请执行以下操作:

$ python -c 'from foo import *; print hello()'

和中间立场:

$ python -c 'from foo import hello; print hello()'

With the -c (command) argument (assuming your file is named foo.py):

$ python -c 'import foo; print foo.hello()'

Alternatively, if you don’t care about namespace pollution:

$ python -c 'from foo import *; print hello()'

And the middle ground:

$ python -c 'from foo import hello; print hello()'

回答 1

只需将其hello()放在函数下方,它将在您执行时执行python your_file.py

对于更整洁的解决方案,您可以使用以下方法:

if __name__ == '__main__':
    hello()

这样,仅当您运行文件时才执行该功能,而不是在导入文件时执行该功能。

Just put hello() somewhere below the function and it will execute when you do python your_file.py

For a neater solution you can use this:

if __name__ == '__main__':
    hello()

That way the function will only be executed if you run the file, not when you import the file.


回答 2

python -c 'from myfile import hello; hello()'这里myfile必须使用Python脚本的基本名称来代替。(例如,myfile.py变为myfile)。

但是,如果hello()在您的Python脚本中是您的“永久”主入口点,那么执行此操作的通常方法如下:

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()

这样,您只需运行python myfile.py或即可执行脚本python -m myfile

此处的一些解释:__name__是一个特殊的Python变量,用于保存当前正在执行的模块的名称,除非从命令行启动模块(在这种情况下为)"__main__"

python -c 'from myfile import hello; hello()' where myfile must be replaced with the basename of your Python script. (E.g., myfile.py becomes myfile).

However, if hello() is your “permanent” main entry point in your Python script, then the usual way to do this is as follows:

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()

This allows you to execute the script simply by running python myfile.py or python -m myfile.

Some explanation here: __name__ is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__".


回答 3

我编写了一个快速的Python小脚本,可以从bash命令行调用它。它使用您要调用的模块,类和方法的名称以及您要传递的参数。我将其称为PyRun并保留了.py扩展名,并使其可用chmod + x PyRun可执行,因此我可以按如下所示快速调用它:

./PyRun PyTest.ClassName.Method1 Param1

将此保存在名为PyRun的文件中

#!/usr/bin/env python
#make executable in bash chmod +x PyRun

import sys
import inspect
import importlib
import os

if __name__ == "__main__":
    cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
    if cmd_folder not in sys.path:
        sys.path.insert(0, cmd_folder)

    # get the second argument from the command line      
    methodname = sys.argv[1]

    # split this into module, class and function name
    modulename, classname, funcname = methodname.split(".")

    # get pointers to the objects based on the string names
    themodule = importlib.import_module(modulename)
    theclass = getattr(themodule, classname)
    thefunc = getattr(theclass, funcname)

    # pass all the parameters from the third until the end of 
    # what the function needs & ignore the rest
    args = inspect.getargspec(thefunc)
    z = len(args[0]) + 2
    params=sys.argv[2:z]
    thefunc(*params)

这是一个示例模块,展示了它是如何工作的。这保存在名为PyTest.py的文件中:

class SomeClass:
 @staticmethod
 def First():
     print "First"

 @staticmethod
 def Second(x):
    print(x)
    # for x1 in x:
    #     print x1

 @staticmethod
 def Third(x, y):
     print x
     print y

class OtherClass:
    @staticmethod
    def Uno():
        print("Uno")

尝试运行以下示例:

./PyRun PyTest.SomeClass.First
./PyRun PyTest.SomeClass.Second Hello
./PyRun PyTest.SomeClass.Third Hello World
./PyRun PyTest.OtherClass.Uno
./PyRun PyTest.SomeClass.Second "Hello"
./PyRun PyTest.SomeClass.Second \(Hello, World\)

请注意最后一个转义括号以将元组作为Second方法的唯一参数传递的示例。

如果为该方法所需的参数传递的参数太少,则会出现错误。如果您通过太多,它将忽略额外费用。该模块必须在当前工作文件夹中,将PyRun放置在路径中的任何位置。

I wrote a quick little Python script that is callable from a bash command line. It takes the name of the module, class and method you want to call and the parameters you want to pass. I call it PyRun and left off the .py extension and made it executable with chmod +x PyRun so that I can just call it quickly as follow:

./PyRun PyTest.ClassName.Method1 Param1

Save this in a file called PyRun

#!/usr/bin/env python
#make executable in bash chmod +x PyRun

import sys
import inspect
import importlib
import os

if __name__ == "__main__":
    cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
    if cmd_folder not in sys.path:
        sys.path.insert(0, cmd_folder)

    # get the second argument from the command line      
    methodname = sys.argv[1]

    # split this into module, class and function name
    modulename, classname, funcname = methodname.split(".")

    # get pointers to the objects based on the string names
    themodule = importlib.import_module(modulename)
    theclass = getattr(themodule, classname)
    thefunc = getattr(theclass, funcname)

    # pass all the parameters from the third until the end of 
    # what the function needs & ignore the rest
    args = inspect.getargspec(thefunc)
    z = len(args[0]) + 2
    params=sys.argv[2:z]
    thefunc(*params)

Here is a sample module to show how it works. This is saved in a file called PyTest.py:

class SomeClass:
 @staticmethod
 def First():
     print "First"

 @staticmethod
 def Second(x):
    print(x)
    # for x1 in x:
    #     print x1

 @staticmethod
 def Third(x, y):
     print x
     print y

class OtherClass:
    @staticmethod
    def Uno():
        print("Uno")

Try running these examples:

./PyRun PyTest.SomeClass.First
./PyRun PyTest.SomeClass.Second Hello
./PyRun PyTest.SomeClass.Third Hello World
./PyRun PyTest.OtherClass.Uno
./PyRun PyTest.SomeClass.Second "Hello"
./PyRun PyTest.SomeClass.Second \(Hello, World\)

Note the last example of escaping the parentheses to pass in a tuple as the only parameter to the Second method.

If you pass too few parameters for what the method needs you get an error. If you pass too many, it ignores the extras. The module must be in the current working folder, put PyRun can be anywhere in your path.


回答 4

将此代码段添加到脚本的底部

def myfunction():
    ...


if __name__ == '__main__':
    globals()[sys.argv[1]]()

您现在可以通过运行来调用函数

python myscript.py myfunction

之所以有效,是因为您要将命令行参数(函数名称的字符串)传递给locals,该字典具有当前本地符号表。最后的括号将使函数被调用。

更新:如果您希望函数从命令行接受参数,则可以这样传递sys.argv[2]

def myfunction(mystring):
    print mystring


if __name__ == '__main__':
    globals()[sys.argv[1]](sys.argv[2])

这样,运行python myscript.py myfunction "hello"将输出hello

add this snippet to the bottom of your script

def myfunction():
    ...


if __name__ == '__main__':
    globals()[sys.argv[1]]()

You can now call your function by running

python myscript.py myfunction

This works because you are passing the command line argument (a string of the function’s name) into locals, a dictionary with a current local symbol table. The parantheses at the end will make the function be called.

update: if you would like the function to accept a parameter from the command line, you can pass in sys.argv[2] like this:

def myfunction(mystring):
    print mystring


if __name__ == '__main__':
    globals()[sys.argv[1]](sys.argv[2])

This way, running python myscript.py myfunction "hello" will output hello.


回答 5

让我们自己简化一点,只使用一个模块…

尝试: pip install compago

然后写:

import compago
app = compago.Application()

@app.command
def hello():
    print "hi there!"

@app.command
def goodbye():
    print "see ya later."

if __name__ == "__main__":
    app.run()

然后像这样使用:

$ python test.py hello
hi there!

$ python test.py goodbye
see ya later.

注意:目前Python 3中存在一个错误,但与Python 2配合使用时效果很好。

编辑:我认为是一个更好的选择,是Google 触发的模块,这也使得传递函数参数变得容易。它与一起安装pip install fire。从他们的GitHub:

这是一个简单的例子。

import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)

然后,可以从命令行运行:

python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

Let’s make this a little easier on ourselves and just use a module…

Try: pip install compago

Then write:

import compago
app = compago.Application()

@app.command
def hello():
    print "hi there!"

@app.command
def goodbye():
    print "see ya later."

if __name__ == "__main__":
    app.run()

Then use like so:

$ python test.py hello
hi there!

$ python test.py goodbye
see ya later.

Note: There’s a bug in Python 3 at the moment, but works great with Python 2.

Edit: An even better option, in my opinion is the module fire by Google which makes it easy to also pass function arguments. It is installed with pip install fire. From their GitHub:

Here’s a simple example.

import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)

Then, from the command line, you can run:

python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

回答 6

有趣的是,如果目标是打印到命令行控制台或执行其他一些分钟的python操作,则可以将输入通过管道传递到python解释器中,如下所示:

echo print("hi:)") | python

以及管道文件

python < foo.py

*请注意,扩展名不必一定是.py才能正常工作。**还请注意,对于bash而言,您可能需要转义字符

echo print\(\"hi:\)\"\) | python

Interestingly enough, if the goal was to print to the command line console or perform some other minute python operation, you can pipe input into the python interpreter like so:

echo print("hi:)") | python

as well as pipe files..

python < foo.py

*Note that the extension does not have to be .py for the second to work. **Also note that for bash you may need to escape the characters

echo print\(\"hi:\)\"\) | python

回答 7

如果安装runp软件包时pip install runp需要运行:

runp myfile.py hello

您可以在以下位置找到存储库:https : //github.com/vascop/runp

If you install the runp package with pip install runp its a matter of running:

runp myfile.py hello

You can find the repository at: https://github.com/vascop/runp


回答 8

我需要在命令行上使用各种python实用程序(范围,字符串等),并为此专门编写了pyfunc工具。您可以使用它来丰富您的命令行使用经验:

 $ pyfunc -m range -a 1 7 2
 1
 3
 5

 $ pyfunc -m string.upper -a test
 TEST

 $ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
 analyze this

I had a requirement of using various python utilities (range, string, etc.) on the command line and had written the tool pyfunc specifically for that. You can use it to enrich you command line usage experience:

 $ pyfunc -m range -a 1 7 2
 1
 3
 5

 $ pyfunc -m string.upper -a test
 TEST

 $ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
 analyze this

回答 9

始终可以使用python命令在命令行中输入python

然后导入您的文件,以便导入example_file

然后使用example_file.hello()运行命令

这避免了每次运行python -c等时都会出现的怪异.pyc复制函数。

也许不像单个命令那样方便,但是它是一个很好的快速修复程序,可从命令行向文件发送文本,并允许您使用python来调用和执行文件。

It is always an option to enter python on the command line with the command python

then import your file so import example_file

then run the command with example_file.hello()

This avoids the weird .pyc copy function that crops up every time you run python -c etc.

Maybe not as convenient as a single-command, but a good quick fix to text a file from the command line, and allows you to use python to call and execute your file.


回答 10

像这样:call_from_terminal.py

# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
    print ip

这在bash中有效。

$ ip='"hi"' ; fun_name='call_from_terminal' 
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi

Something like this: call_from_terminal.py

# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
    print ip

This works in bash.

$ ip='"hi"' ; fun_name='call_from_terminal' 
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi

回答 11

下面是Odd_Even_function.py文件,其中包含函数的定义。

def OE(n):
    for a in range(n):
        if a % 2 == 0:
            print(a)
        else:
            print(a, "ODD")

现在,从下面的命令提示符处调用相同的选项对我有用。

选项1 exe \ python.exe -c“导入Odd_Even_function; Odd_Even_function.OE(100)”的完整路径

选项2 exe \ python.exe -c“从Odd_Even_function import OE; OE(100)”的完整路径

谢谢。

Below is the Odd_Even_function.py file that has the definition of the function.

def OE(n):
    for a in range(n):
        if a % 2 == 0:
            print(a)
        else:
            print(a, "ODD")

Now to call the same from Command prompt below are the options worked for me.

Options 1 Full path of the exe\python.exe -c “import Odd_Even_function; Odd_Even_function.OE(100)”

Option 2 Full path of the exe\python.exe -c “from Odd_Even_function import OE; OE(100)”

Thanks.


回答 12

此函数无法从命令行运行,因为它返回的值将不可用。您可以删除退货并改为使用打印

This function cannot be run from the command line as it returns a value which will go unhanded. You can remove the return and use print instead


回答 13

使用python-c工具(pip install python-c),然后简单地编写:

$ python-c foo 'hello()'

或在python文件中没有函数名冲突的情况下:

$ python-c 'hello()'

Use the python-c tool (pip install python-c) and then simply write:

$ python-c foo 'hello()'

or in case you have no function name clashes in your python files:

$ python-c 'hello()'

回答 14

首先,您必须按照他们告诉您的方式调用该函数,否则该功能将在输出中不显示任何内容,之后保存文件并通过右键单击将文件的路径复制到文件的文件夹,然后单击“复制文件”转到终端并输入:-cd“文件的路径”-python“例如文件的名称(main.py)”,之后它将显示代码的输出。

First you have to call the function as they told you or the founction will display nothing in the output, after that save the file and copy the path of the file by right click to the folder of the file and click on”copy file” then go to terminal and write: – cd “the path of the file” – python “name of the file for example (main.py)” after that it will display the output of your code.


回答 15

安装Spyder,让您的生活更轻松。打开文件,然后运行它(单击绿色箭头)。之后,您的hello()方法已定义并为IPython控制台所知,因此您可以从控制台中调用它。

Make your life easier, install Spyder. Open your file then run it (click the green arrow). Afterwards your hello() method is defined and known to the IPython Console, so you can call it from the console.


如何在Python中访问命令行参数?

问题:如何在Python中访问命令行参数?

我使用python创建我的项目设置设置,但我需要获取命令行参数的帮助。

我在终端上尝试了这个:

$python myfile.py var1 var2 var3

在我的Python文件中,我想使用所有输入的变量。

I use python to create my project settings setup, but I need help getting the command line arguments.

I tried this on the terminal:

$python myfile.py var1 var2 var3

In my Python file, I want to use all variables that are input.


回答 0

Python教程对此进行了解释

import sys

print(sys.argv)

更具体地说,如果您运行python example.py one two three

>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']

Python tutorial explains it:

import sys

print(sys.argv)

More specifically, if you run python example.py one two three:

>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']

回答 1

import sys

sys.argv[1:]

将为您提供参数列表(不包括python文件的名称)

import sys

sys.argv[1:]

will give you a list of arguments (not including the name of the python file)


回答 2

我强烈建议argparsePython 2.7及更高版本随附。

argparse模块减少了样板代码,并使您的代码更健壮,因为该模块可以处理所有标准用例(包括子命令),为您生成帮助和用法,检查并清理用户输入-您在使用时需要担心的所有事情正在使用sys.argv方法。它是免费的(内置)。

这里有个小例子:

import argparse

parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)

和输出为 python prog.py -h

usage: simple_example [-h] counter

positional arguments:
  counter     counter will be increased by 1 and printed.

optional arguments:
  -h, --help  show this help message and exit

python prog.py 1您所期望的:

2

I highly recommend argparse which comes with Python 2.7 and later.

The argparse module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input – all stuff you have to worry about when you are using sys.argv approach. And it is for free (built-in).

Here a small example:

import argparse

parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)

and the output for python prog.py -h

usage: simple_example [-h] counter

positional arguments:
  counter     counter will be increased by 1 and printed.

optional arguments:
  -h, --help  show this help message and exit

and for python prog.py 1 as you would expect:

2

回答 3

Python代码:

import sys

# main
param_1= sys.argv[1] 
param_2= sys.argv[2] 
param_3= sys.argv[3]  
print 'Params=', param_1, param_2, param_3

调用:

$python myfile.py var1 var2 var3

输出:

Params= var1 var2 var3 

Python code:

import sys

# main
param_1= sys.argv[1] 
param_2= sys.argv[2] 
param_3= sys.argv[3]  
print 'Params=', param_1, param_2, param_3

Invocation:

$python myfile.py var1 var2 var3

Output:

Params= var1 var2 var3 

回答 4

您可以使用 sys.argv用来获取参数列表。

如果您需要访问各个元素,则可以使用

sys.argv[i]  

i索引在哪里,0将为您提供正在执行的python文件名。之后的任何索引都是传递的参数。

You can use sys.argv to get the arguments as a list.

If you need to access individual elements, you can use

sys.argv[i]  

where i is index, 0 will give you the python filename being executed. Any index after that are the arguments passed.


回答 5

如果您这样称呼它: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

与数组类似,您也拥有sys.argv[0]始终是当前工作目录的数组。

If you call it like this: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

Similar to arrays you also have sys.argv[0] which is always the current working directory.


回答 6

我可以想到的一些其他事项。

正如@allsyed所说,sys.argv提供了一个组件列表(包括程序名称),因此,如果您想知道通过命令行传递的元素数量,可以使用len()来确定它。基于此,如果用户未传递特定数量的参数,则可以设计异常/错误消息。

另外,如果您正在寻找一种更好的方式来处理命令行参数,我建议您查看https://docs.python.org/2/howto/argparse.html

Some additional things that I can think of.

As @allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn’t pass specific number of parameters.

Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html


如何读取/处理命令行参数?

问题:如何读取/处理命令行参数?

我原本是C程序员。我看到了许多花招和“技巧”来阅读许多不同的论点。

Python程序员可以通过哪些方式做到这一点?

有关


回答 0

标准库中的规范解决方案是argparsedocs):

这是一个例子:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
                    help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")

args = parser.parse_args()

argparse 支持(除其他外):

  • 任意顺序的多个选项。
  • 短期和长期选择。
  • 默认值。
  • 生成使用帮助消息。

The canonical solution in the standard library is argparse (docs):

Here is an example:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
                    help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")

args = parser.parse_args()

argparse supports (among other things):

  • Multiple options in any order.
  • Short and long options.
  • Default values.
  • Generation of a usage help message.

回答 1

import sys

print("\n".join(sys.argv))

sys.argv 是一个列表,其中包含在命令行上传递给脚本的所有参数。

基本上,

import sys
print(sys.argv[1:])
import sys

print("\n".join(sys.argv))

sys.argv is a list that contains all the arguments passed to the script on the command line.

Basically,

import sys
print(sys.argv[1:])

回答 2

出于这些原因,只是为了使argparse传福音就更好了..本质上:

(从链接复制)

  • argparse模块可以处理位置和可选参数,而optparse仅可以处理可选参数

  • argparse对您的命令行界面应该是什么样的并不教条-支持-file或/ file之类的选项,以及必需的选项。Optparse拒绝支持这些功能,而是偏向于纯度而不是实用性

  • argparse会生成更多有用的用法消息,包括根据您的参数确定的命令行用法,以及有关位置参数和可选参数的帮助消息。optparse模块需要您编写自己的用法字符串,并且无法显示位置参数的帮助。

  • argparse支持消耗可变数量的命令行args的操作,而optparse要求事先知道确切数量的参数(例如1、2或3)

  • argparse支持分派到子命令allow_interspersed_args的解析器,而optparse需要手动设置 和执行解析器分派

和我个人最喜欢的:

  • argparse允许add_argument() 使用简单的可调用对象来指定类型和操作参数,而optparse则需要侵入类属性,例如 STORE_ACTIONSCHECK_METHODS进行正确的参数检查。

Just going around evangelizing for argparse which is better for these reasons.. essentially:

(copied from the link)

  • argparse module can handle positional and optional arguments, while optparse can handle only optional arguments

  • argparse isn’t dogmatic about what your command line interface should look like – options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality

  • argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.

  • argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance

  • argparse supports parsers that dispatch to sub-commands, while optparse requires setting allow_interspersed_args and doing the parser dispatch manually

And my personal favorite:

  • argparse allows the type and action parameters to add_argument() to be specified with simple callables, while optparse requires hacking class attributes like STORE_ACTIONS or CHECK_METHODS to get proper argument checking

回答 3

还有argparsestdlib模块stdlib模块上的“改进” optparse)。argparse简介中的示例:

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=range(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

用法:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10

There is also argparse stdlib module (an “impovement” on stdlib’s optparse module). Example from the introduction to argparse:

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=range(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

Usage:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10

回答 4

一种方法是使用sys.argv。这将打印脚本名称作为第一个参数以及传递给它的所有其他参数。

import sys

for arg in sys.argv:
    print arg

One way to do it is using sys.argv. This will print the script name as the first argument and all the other parameters that you pass to it.

import sys

for arg in sys.argv:
    print arg

回答 5

docopt库是真的光滑。它从应用程序的用法字符串中构建一个参数dict。

例如来自docopt自述文件:

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)

The docopt library is really slick. It builds an argument dict from the usage string for your app.

Eg from the docopt readme:

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)

回答 6

如果您需要快速但不太灵活的东西

main.py:

import sys

first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)

然后跑 python main.py James Smith

产生以下输出:

你好詹姆斯史密斯

If you need something fast and not very flexible

main.py:

import sys

first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)

Then run python main.py James Smith

to produce the following output:

Hello James Smith


回答 7

#set default args as -h , if no args:
if len(sys.argv) == 1: sys.argv[1:] = ["-h"]
#set default args as -h , if no args:
if len(sys.argv) == 1: sys.argv[1:] = ["-h"]

回答 8

我自己使用optparse,但真的很喜欢Simon Willison在他最近引入的optfunc库中的发展方向。它的工作原理是:

“对函数定义(包括其参数及其默认值)进行自省,并使用其来构建命令行参数解析器。”

因此,例如,此函数定义:

def geocode(s, api_key='', geocoder='google', list_geocoders=False):

变成以下optparse帮助文本:

    Options:
      -h, --help            show this help message and exit
      -l, --list-geocoders
      -a API_KEY, --api-key=API_KEY
      -g GEOCODER, --geocoder=GEOCODER

I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced optfunc library. It works by:

“introspecting a function definition (including its arguments and their default values) and using that to construct a command line argument parser.”

So, for example, this function definition:

def geocode(s, api_key='', geocoder='google', list_geocoders=False):

is turned into this optparse help text:

    Options:
      -h, --help            show this help message and exit
      -l, --list-geocoders
      -a API_KEY, --api-key=API_KEY
      -g GEOCODER, --geocoder=GEOCODER

回答 9

我喜欢stdlib中的getopt,例如:

try:
    opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err: 
    usage(err)

for opt, arg in opts:
    if opt in ('-h', '--help'): 
        usage()

if len(args) != 1:
    usage("specify thing...")

最近,我一直在包装类似的东西,以使事情变得不太冗长(例如,使“ -h”隐式)。

I like getopt from stdlib, eg:

try:
    opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err: 
    usage(err)

for opt, arg in opts:
    if opt in ('-h', '--help'): 
        usage()

if len(args) != 1:
    usage("specify thing...")

Lately I have been wrapping something similiar to this to make things less verbose (eg; making “-h” implicit).


回答 10

Pocoo的点击更加直观,所需模板更少,并且至少与argparse一样强大。

到目前为止,我遇到的唯一弱点是您不能做太多自定义来帮助页面,但这通常不是必需的,docopt似乎是明确的选择。

Pocoo’s click is more intuitive, requires less boilerplate, and is at least as powerful as argparse.

The only weakness I’ve encountered so far is that you can’t do much customization to help pages, but that usually isn’t a requirement and docopt seems like the clear choice when it is.


回答 11

如您所见,optparse “ optparse模块已弃用,将不再进一步开发;argparse模块将继续开发。”

As you can see optparse “The optparse module is deprecated with and will not be developed further; development will continue with the argparse module.”


回答 12

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h

Ref-link: https://docs.python.org/3.3/library/argparse.html
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h

Ref-link: https://docs.python.org/3.3/library/argparse.html

回答 13

您可能对我编写的一个Python小模块感兴趣,该模块使命令行参数的处理更加容易(开源且免费使用)-Commando

You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) – Commando


回答 14

我建议将docopt看作是其他替代品的简单替代方案。

docopt是一个新项目,可以通过解析–help使用情况消息来工作,而不是要求您自己实现一切。您只需要将使用情况消息以POSIX格式输入即可。

I recommend looking at docopt as a simple alternative to these others.

docopt is a new project that works by parsing your –help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.


回答 15

另一个选择是argh。它基于argparse构建,并允许您编写如下内容:

import argh

# declaring:

def echo(text):
    "Returns given word as is."
    return text

def greet(name, greeting='Hello'):
    "Greets the user with given name. The greeting is customizable."
    return greeting + ', ' + name

# assembling:

parser = argh.ArghParser()
parser.add_commands([echo, greet])

# dispatching:

if __name__ == '__main__':
    parser.dispatch()

它会自动生成帮助,等等,您可以使用装饰器提供有关arg解析工作方式的额外指导。

Yet another option is argh. It builds on argparse, and lets you write things like:

import argh

# declaring:

def echo(text):
    "Returns given word as is."
    return text

def greet(name, greeting='Hello'):
    "Greets the user with given name. The greeting is customizable."
    return greeting + ', ' + name

# assembling:

parser = argh.ArghParser()
parser.add_commands([echo, greet])

# dispatching:

if __name__ == '__main__':
    parser.dispatch()

It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.


回答 16

我的解决方案是entrypoint2。例:

from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True): 
    ''' This function writes report.

    :param file: write report to FILE
    :param quiet: don't print status messages to stdout
    '''
    print file,quiet

帮助文字:

usage: report.py [-h] [-q] [--debug] file

This function writes report.

positional arguments:
  file         write report to FILE

optional arguments:
  -h, --help   show this help message and exit
  -q, --quiet  don't print status messages to stdout
  --debug      set logging level to DEBUG

My solution is entrypoint2. Example:

from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True): 
    ''' This function writes report.

    :param file: write report to FILE
    :param quiet: don't print status messages to stdout
    '''
    print file,quiet

help text:

usage: report.py [-h] [-q] [--debug] file

This function writes report.

positional arguments:
  file         write report to FILE

optional arguments:
  -h, --help   show this help message and exit
  -q, --quiet  don't print status messages to stdout
  --debug      set logging level to DEBUG

Gitsome-增强型Git/GitHub命令行界面(CLI)。GitHub和GitHub企业的官方集成:https://github.com/works-with/category/desktop-tools

一个Official Integration对于GitHub和GitHub Enterprise

为什么gitsome

Git命令行

虽然标准的Git命令行是管理基于Git的repo的一个很好的工具,但是它可以很难记住这个用法地址为:

  • 150多个瓷器和管道命令
  • 无数特定于命令的选项
  • 标签和分支等资源

Git命令行不与GitHub集成,强制您在命令行和浏览器之间切换

gitsome-具有自动完成功能的增压Git/GitHub CLI

gitsome旨在通过专注于以下方面来增强您的标准git/shell界面:

  • 提高易用性
  • 提高工作效率

深度GitHub集成

并不是所有的GitHub工作流都能在终端中很好地工作;gitsome试图将目标对准那些这样做的人

gitsome包括29个与一起使用的GitHub集成命令ALL外壳:

$ gh <command> [param] [options]

gh命令以及Git-Extrashub解锁更多GitHub集成的命令!

带有交互式帮助的Git和GitHub自动完成程序

您可以运行可选壳牌:

 $ gitsome

要启用自动完成交互式帮助对于以下内容:

通用自动补全程序

gitsome自动完成以下内容:

  • Shell命令
  • 文件和目录
  • 环境变量
  • 手册页
  • python

要启用其他自动完成,请查看Enabling Bash Completions部分

鱼式自动建议

gitsome支持鱼式自动建议。使用right arrow完成建议的关键

Python REPL

gitsome由以下人员提供动力xonsh,它支持Python REPL

在shell命令旁边运行Python命令:

附加内容xonsh功能可在xonsh tutorial

命令历史记录

gitsome跟踪您输入的命令并将其存储在~/.xonsh_history.json使用向上和向下箭头键循环查看命令历史记录

可自定义的突出显示

可以控制用于突出显示的ansi颜色,方法是更新~/.gitsomeconfig文件

颜色选项包括:

'black', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white'

对于无颜色,请将值设置为Nonewhite在某些终端上可能显示为浅灰色

可用的平台

gitsome适用于Mac、Linux、Unix、Windows,以及Docker

待办事项

并不是所有的GitHub工作流都能在终端中很好地工作;gitsome试图将目标对准那些这样做的人

  • 添加其他GitHub API集成

gitsome才刚刚开始。请随意……contribute!

索引

GitHub集成命令

安装和测试

杂项

GitHub集成命令语法

用法:

$ gh <command> [param] [options]

GitHub集成命令列表

  configure            Configure gitsome.
  create-comment       Create a comment on the given issue.
  create-issue         Create an issue.
  create-repo          Create a repo.
  emails               List all the user's registered emails.
  emojis               List all GitHub supported emojis.
  feed                 List all activity for the given user or repo.
  followers            List all followers and the total follower count.
  following            List all followed users and the total followed count.
  gitignore-template   Output the gitignore template for the given language.
  gitignore-templates  Output all supported gitignore templates.
  issue                Output detailed information about the given issue.
  issues               List all issues matching the filter.
  license              Output the license template for the given license.
  licenses             Output all supported license templates.
  me                   List information about the logged in user.
  notifications        List all notifications.
  octo                 Output an Easter egg or the given message from Octocat.
  pull-request         Output detailed information about the given pull request.
  pull-requests        List all pull requests.
  rate-limit           Output the rate limit.  Not available for Enterprise.
  repo                 Output detailed information about the given filter.
  repos                List all repos matching the given filter.
  search-issues        Search for all issues matching the given query.
  search-repos         Search for all repos matching the given query.
  starred              Output starred repos.
  trending             List trending repos for the given language.
  user                 List information about the given user.
  view                 View the given index in the terminal or a browser.

GitHub集成命令参考:COMMANDS.md

请参阅GitHub Integration Commands Reference in COMMANDS.md对于详细讨论所有GitHub集成命令、参数、选项和示例

请查看下一节,了解快速参考

GitHub集成命令快速参考

配置gitsome

要与GitHub正确集成,您必须首先配置gitsome

$ gh configure

对于GitHub Enterprise用户,使用-e/--enterprise标志:

$ gh configure -e

列表源

列出您的新闻源

$ gh feed

列出用户的活动摘要

查看您的活动订阅源或其他用户的活动订阅源,也可以选择使用寻呼机-p/--pager这个pager option可用于许多命令

$ gh feed donnemartin -p

列出回购的活动提要

$ gh feed donnemartin/gitsome -p

列出通知

$ gh notifications

列出拉式请求

查看您的回购的所有拉式请求:

$ gh pull-requests

过滤问题

查看您提到的所有未决问题:

$ gh issues --issue_state open --issue_filter mentioned

查看所有问题,只筛选分配给您的问题,而不考虑状态(打开、关闭):

$ gh issues --issue_state all --issue_filter assigned

有关过滤和州限定词的更多信息,请访问gh issues参考位置COMMANDS.md

过滤星级报告

$ gh starred "repo filter"

搜索问题和报告

搜索问题

+1最多的搜索问题:

$ gh search-issues "is:open is:issue sort:reactions-+1-desc" -p

评论最多的搜索问题:

$ gh search-issues "is:open is:issue sort:comments-desc" -p

使用“需要帮助”标签搜索问题:

$ gh search-issues "is:open is:issue label:\"help wanted\"" -p

已标记您的用户名的搜索问题@donnemartin

$ gh search-issues "is:issue donnemartin is:open" -p

搜索您所有未解决的私人问题:

$ gh search-issues "is:open is:issue is:private" -p

有关查询限定符的更多信息,请访问searching issues reference

搜索报告

搜索2015年或之后创建的所有Python repos,>=1000星:

$ gh search-repos "created:>=2015-01-01 stars:>=1000 language:python" --sort stars -p

有关查询限定符的更多信息,请访问searching repos reference

列出趋势报告和开发人员

查看趋势回购:

$ gh trending [language] [-w/--weekly] [-m/--monthly] [-d/--devs] [-b/--browser]

查看趋势DEV(目前仅浏览器支持DEV):

$ gh trending [language] --devs --browser

查看内容

这个view命令

查看前面列出的通知、拉取请求、问题、回复、用户等,HTML格式适合您的终端,也可以选择在您的浏览器中查看:

$ gh view [#] [-b/--browser]

这个issue命令

查看问题:

$ gh issue donnemartin/saws/1

这个pull-request命令

查看拉取请求:

$ gh pull-request donnemartin/awesome-aws/2

设置.gitignore

列出所有可用的.gitignore模板:

$ gh gitignore-templates

设置您的.gitignore

$ gh gitignore-template Python > .gitignore

设置LICENSE

列出所有可用的LICENSE模板:

$ gh licenses

设置您的或LICENSE

$ gh license MIT > LICENSE

召唤十月猫

在十月猫那天打电话说出给定的信息或复活节彩蛋:

$ gh octo [say]

查看配置文件

查看用户的配置文件

$ gh user octocat

查看您的个人资料

使用查看您的个人资料gh user [YOUR_USER_ID]命令或使用以下快捷方式:

$ gh me

创建评论、问题和报告

创建评论:

$ gh create-comment donnemartin/gitsome/1 -t "hello world"

创建问题:

$ gh create-issue donnemartin/gitsome -t "title" -b "body"

创建回购:

$ gh create-repo gitsome

选项:在寻呼机中查看

许多gh命令支持-p/--pager在寻呼机中显示结果的选项(如果可用)

用法:

$ gh <command> [param] [options] -p
$ gh <command> [param] [options] --pager

选项:在浏览器中查看

许多gh命令支持-b/--browser在默认浏览器(而不是终端)中显示结果的选项

用法:

$ gh <command> [param] [options] -b
$ gh <command> [param] [options] --browser

请参阅COMMANDS.md有关所有GitHub集成命令、参数、选项和示例的详细列表

记住这些命令有困难吗?看看手边的autocompleter with interactive help来指导您完成每个命令

注意,您可以将gitsome与其他实用程序(如Git-Extras

安装

PIP安装

gitsome托管在PyPI将安装以下命令gitsome

$ pip3 install gitsome

您还可以安装最新的gitsome来自GitHub源,可能包含尚未推送到PyPI的更改:

$ pip3 install git+https://github.com/donnemartin/gitsome.git

如果您没有安装在virtualenv,您可能需要运行sudo

$ sudo pip3 install gitsome

pip3

根据您的设置,您可能还希望运行pip3使用-H flag

$ sudo -H pip3 install gitsome

对于大多数Linux用户来说,pip3可以使用python3-pip套餐

例如,Ubuntu用户可以运行:

$ sudo apt-get install python3-pip

看这个ticket有关更多详细信息,请参阅

虚拟环境安装

您可以将Python包安装在virtualenv要避免依赖项或权限的潜在问题,请执行以下操作

如果您是Windows用户,或者如果您想了解更多有关virtualenv,看看这个guide

安装virtualenvvirtualenvwrapper

$ pip3 install virtualenv
$ pip3 install virtualenvwrapper
$ export WORKON_HOME=~/.virtualenvs
$ source /usr/local/bin/virtualenvwrapper.sh

创建gitsomevirtualenv并安装gitsome

$ mkvirtualenv gitsome
$ pip3 install gitsome

如果pip安装不起作用,您可能默认运行的是Python2。检查您正在运行的Python版本:

$ python --version

如果上面的调用结果是Python 2,请找到Python 3的路径:

$ which python3  # Python 3 path for mkvirtualenv's --python option

如果需要,安装Python 3。调用时设置Python版本mkvirtualenv

$ mkvirtualenv --python [Python 3 path from above] gitsome
$ pip3 install gitsome

如果要激活gitsomevirtualenv稍后再次运行:

$ workon gitsome

要停用gitsomevirtualenv,运行:

$ deactivate

作为Docker容器运行

您可以在Docker容器中运行gitome,以避免安装Python和pip3当地的。要安装Docker,请查看official Docker documentation

一旦安装了docker,您就可以运行gitome:

$ docker run -ti --rm mariolet/gitsome

您可以使用Docker卷让gitome访问您的工作目录、本地的.gitSomeconfig和.gitconfig:

$ docker run -ti --rm -v $(pwd):/src/              \
   -v ${HOME}/.gitsomeconfig:/root/.gitsomeconfig  \
   -v ${HOME}/.gitconfig:/root/.gitconfig          \
   mariolet/gitsome

如果您经常运行此命令,则可能需要定义别名:

$ alias gitsome="docker run -ti --rm -v $(pwd):/src/              \
                  -v ${HOME}/.gitsomeconfig:/root/.gitsomeconfig  \
                  -v ${HOME}/.gitconfig:/root/.gitconfig          \
                  mariolet/gitsome"

要从源构建Docker映像,请执行以下操作:

$ git clone https://github.com/donnemartin/gitsome.git
$ cd gitsome
$ docker build -t gitsome .

启动gitsome

安装后,运行可选的gitsome带有交互式帮助的自动完成程序:

$ gitsome

运行可选的gitsomeShell将为您提供自动完成、交互式帮助、鱼式建议、Python REPL等

正在运行gh命令

运行GitHub集成命令:

$ gh <command> [param] [options]

注意:运行gitsome不需要执行外壳程序gh命令。之后installinggitsome你可以跑gh来自任何shell的命令

运行gh configure命令

要与GitHub正确集成,gitsome必须正确配置:

$ gh configure

针对GitHub企业用户

使用-e/--enterprise标志:

$ gh configure -e

要查看更多详细信息,请访问gh configure部分

启用Bash完成

默认情况下,gitsome查看以下内容locations to enable bash completions

要添加其他bash完成,请更新~/.xonshrc包含bash完成位置的文件

如果~/.xonshrc不存在,请创建它:

$ touch ~/.xonshrc

例如,如果在/usr/local/etc/my_bash_completion.d/completion.bash,将以下行添加到~/.xonshrc

$BASH_COMPLETIONS.append('/usr/local/etc/my_bash_completion.d/completion.bash')

您将需要重新启动gitsome要使更改生效,请执行以下操作

正在启用gh在外部完成制表符gitsome

你可以跑gh外部的命令gitsome外壳完成器。要启用gh此工作流的制表符完成,请将gh_complete.sh本地文件

让bash知道可以完成gh当前会话中的命令:

$ source /path/to/gh_complete.sh

要为所有终端会话启用制表符完成,请将以下内容添加到您的bashrc文件:

source /path/to/gh_complete.sh

重新加载您的bashrc

$ source ~/.bashrc

提示:.是的缩写source,因此您可以改为运行以下命令:

$ . ~/.bashrc

对于Zsh用户

zsh包括与bash完成兼容的模块

下载gh_complete.sh文件,并将以下内容附加到您的.zshrc

autoload bashcompinit
bashcompinit
source /path/to/gh_complete.sh

重新加载您的zshrc

 $ source ~/.zshrc

可选:安装PILPillow

将化身显示为gh megh user命令需要安装可选的PILPillow依赖性

Windows*和Mac:

$ pip3 install Pillow

*请参阅Windows Support有关化身限制的部分

Ubuntu用户,看看这些instructions on askubuntu

支持的Python版本

  • Python 3.4
  • Python 3.5
  • Python 3.6
  • Python 3.7

gitsome由以下人员提供动力xonsh,它当前不支持Python2.x,如本文中所讨论的ticket

支持的平台

  • Mac OS X
    • 在OS X 10.10上测试
  • Linux、Unix
    • 在Ubuntu 14.04 LTS上测试
  • 窗口
    • 在Windows 10上测试

Windows支持

gitsome已在Windows 10上进行了测试,cmdcmder

虽然您可以使用标准的Windows命令提示符,但使用这两种命令提示符都可能会有更好的体验cmderconemu

纯文本化身

命令gh usergh me将永远拥有-t/--text_avatar标志已启用,因为img2txt不支持Windows上的ANSI头像

配置文件

在Windows上,.gitsomeconfig 文件可在以下位置找到%userprofile%例如:

C:\Users\dmartin\.gitsomeconfig

开发人员安装

如果您有兴趣为gitsome,请运行以下命令:

$ git clone https://github.com/donnemartin/gitsome.git
$ cd gitsome
$ pip3 install -e .
$ pip3 install -r requirements-dev.txt
$ gitsome
$ gh <command> [param] [options]

pip3

如果您在安装时收到一个错误,提示您需要Python 3.4+,这可能是因为您的pip命令是为旧版本的Python配置的。要解决此问题,建议安装pip3

$ sudo apt-get install python3-pip

看这个ticket有关更多详细信息,请参阅

持续集成

有关持续集成的详细信息,请访问Travis CI

单元测试和代码覆盖率

在活动的Python环境中运行单元测试:

$ python tests/run_tests.py

使用运行单元测试tox在多个Python环境中:

$ tox

文档

源代码文档将很快在Readthedocs.org请查看source docstrings

运行以下命令构建文档:

$ scripts/update_docs.sh

贡献

欢迎投稿!

回顾Contributing Guidelines有关如何执行以下操作的详细信息,请执行以下操作:

  • 提交问题
  • 提交拉式请求

学分

联系信息

请随时与我联系,讨论任何问题、问题或评论

我的联系信息可以在我的GitHub page

许可证

我在开放源码许可下向您提供此存储库中的代码和资源。因为这是我的个人存储库,您获得的我的代码和资源的许可证来自我,而不是我的雇主(Facebook)

Copyright 2016 Donne Martin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Google-images-download 从“Google Images”下载数百张图片的Python脚本。这是一个随时可以运行的代码!

Google图片下载

Python脚本,用于“搜索”和“下载”数百张谷歌图片到本地硬盘!

文档

免责声明

这个程序可以让你从谷歌下载大量图片。请不要下载或使用任何违反其版权条款的图片。Google Images是一个搜索引擎,它只对图像进行索引,并允许您找到它们。它不生产自己的图像,因此,它没有任何图像的版权。图像的原始创作者拥有版权

在美国发布的图像自动受其所有者的版权保护,即使它们没有明确带有版权警告。除非在“合理使用”的情况下,否则您不得在未经版权所有者许可的情况下复制版权图像,否则您可能会面临遇到律师警告、停止和停止函以及版权诉讼的风险。请在使用前非常小心!此脚本/代码仅用于教育目的