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.
# 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.
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)
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.0Summary:TensorFlow helps the tensors flow
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?
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).
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可执行,因此我可以按如下所示快速调用它:
./PyRunPyTest.ClassName.Method1Param1
将此保存在名为PyRun的文件中
#!/usr/bin/env python#make executable in bash chmod +x PyRunimport 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 notin 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的文件中:
classSomeClass:@staticmethoddefFirst():print"First"@staticmethoddefSecond(x):print(x)# for x1 in x:# print x1@staticmethoddefThird(x, y):print x
print y
classOtherClass:@staticmethoddefUno():print("Uno")
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")
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.
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.
import fire
classCalculator(object):"""A simple calculator class."""def double(self, number):return2* number
if __name__ =='__main__':
fire.Fire(Calculator)
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)
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
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
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
# 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")
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.
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.
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 1and printed.
optional arguments:-h,--help show this help message and exit
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
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.
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
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.
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
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
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.
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()
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.
from entrypoint2 import entrypoint
@entrypointdef 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
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
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.
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.