这个问题可能被认为是多余的,但为了我的辩护,我已经考虑了类似的问题并给出了解决方案,但它们对我不起作用(或者我只是不理解它们),正如我将要展示的那样。 / p>
我想做什么: 我用pyinstaller构建了几个python脚本,每个脚本都是命令行工具(使用argparse接受几个参数)。它们都可以在pycharm的终端和Ubuntu终端中按预期工作。现在,我希望每个脚本都是一个模块,可以从另一个传递必需参数的python脚本中调用,就像在终端中一样。
这是原始脚本之一(我稍微缩短了脚本,以便它作为一个最小的例子):
import sys
import argparse
import getpass
if len(sys.argv) < 2:
print "You haven't specified any arguments. Use -h to get more details on how to use this command."
sys.exit(1)
parser = argparse.ArgumentParser()
parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server')
parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server')
parser.add_argument('--node', '-n', type=str, default=None,
help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"')
parser.add_argument('-url', type=str, default='https://my.server.de',
help="URL of the WebCTRL server as e.g. http://google.de")
args = parser.parse_args()
if args.username is None:
print 'No user name specified. Login to WebCTRL needs a user name and password. Check all options for this command via -h'
sys.exit(1)
else:
username = args.username
if args.password is None:
password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ')
else:
password = args.password
if args.node is None:
print 'No path to a node specified. Check all options for this command via -h'
sys.exit(1)
if args.url is None:
print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de'
sys.exit(1)
else:
wsdlFile = args.url + '/_common/webservices/Eval?wsdl'
# This doesn't belong to my original code. It's rather for demonstration:
# Print the arguments and leave the script
print 'Username: ' + args.username
print 'Node: ' + args.node
print 'URL: ' + args.url
sys.exit(0)
正如我所说:从我的IDE(Pycharm)......
$ python wc_query_test.py -u wsdl -n /trees/geographic
No password specified via -p. Please enter your WebCTRL login password:
Username: wsdl
Node: /trees/geographic
URL: https://my.server.de
...并且从Ubuntu终端它可以正常工作:
$ pyinstaller --distpath dist/. wc_query_test.py
$ ./dist/wc_query_test/wc_query_test -u wsdl -n /trees/geographic
No password specified via -p. Please enter your WebCTRL login password:
Username: wsdl
Node: /trees/geographic
URL: https://my.server.de
来实际问题: 我希望脚本wc_query_test.py是一个可以导入到另一个python脚本中的模块,并在那里执行,就像在命令行中一样传递参数。为实现这一目标,我遵循了@ Waylan在stackoverflow question中的说明。
这是我提出的代码(wc_query_test.py):
import sys
import argparse
import getpass
def main(**kwargs):
if kwargs.username is None:
print 'No user name specified. Login to WebCTRL needs a user name and password. Check all options for this command via -h'
sys.exit(1)
else:
username = kwargs.username
if kwargs.password is None:
password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ')
else:
password = kwargs.password
if kwargs.node is None:
print 'No path to a node specified. Check all options for this command via -h'
sys.exit(1)
if kwargs.url is None:
print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de'
sys.exit(1)
else:
wsdlFile = kwargs.url + '/_common/webservices/Eval?wsdl'
# This doesn't belong to my original code. It's rather for demonstration:
# Print the arguments and leave the script
print 'Username: ' + username
print 'Node: ' + kwargs.node
print 'URL: ' + kwargs.url
sys.exit(0)
def run():
parser = argparse.ArgumentParser()
parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server')
parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server')
parser.add_argument('--node', '-n', type=str, default=None,
help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"')
parser.add_argument('-url', type=str, default='https://my.server.de',
help="URL of the WebCTRL server as e.g. http://google.de")
args = parser.parse_args()
main(**args)
...以及导入模块并调用它的脚本(test.py):
import wc_query_test
wc_query_test.main(username='wsdl', password='aaaaaa', node='/trees/geographic')
当我在python终端中运行时,我得到:
~/PycharmProjects/webctrl$ python wc_query_test.py
~/PycharmProjects/webctrl$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
wc_query_test.main(username='wsdl', password='aaaaaa', node='/trees/geographic/#geb_g', url='https://webctrl.rz-berlin.mpg.de')
File "/home/stefan/PycharmProjects/webctrl/wc_query_test.py", line 23, in main
if kwargs.username is None:
AttributeError: 'dict' object has no attribute 'username'
运行wc_query_test.py没有输出,我明白为什么会这样。那只是一个考验。但是运行test.py也会产生错误。我知道为什么这不起作用,但我不能用语言表达。这个run()方法怎么样?拥有它有意义吗?我如何修改我的代码以获得“我想做什么:”中描述的这种双重功能?提前感谢您的帮助!
更新
我摆脱了错误信息。我换了,例如kwargs.username
到kwargs.get('username')
,因为kwargs是一本字典。代码现在看起来像这样:
import sys
import argparse
import getpass
def main(**kwargs):
if kwargs.get('username') is None:
print 'No user name specified. Login to WebCTRL needs a user name and password. Check all options for this command via -h'
sys.exit(1)
else:
username = kwargs.get('username')
if kwargs.get('password') is None:
password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ')
else:
password = kwargs.get('password')
if kwargs.get('node') is None:
print 'No path to a node specified. Check all options for this command via -h'
sys.exit(1)
if kwargs.get('url') is None:
print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de'
sys.exit(1)
else:
wsdlFile = kwargs.get('url') + '/_common/webservices/Eval?wsdl'
# This doesn't belong to my original code. It's rather for demonstration:
# Print the arguments and leave the script
print 'Username: ' + username
print 'Node: ' + kwargs.get('node')
print 'URL: ' + kwargs.get('url')
sys.exit(0)
def run():
parser = argparse.ArgumentParser()
parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server')
parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server')
parser.add_argument('--node', '-n', type=str, default=None,
help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"')
parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de',
help="URL of the WebCTRL server as e.g. http://google.de")
args = parser.parse_args()
main(**args)
在python终端中运行它会按预期产生:
$ python test.py
Username: wsdl
Node: /trees/geographic
URL: https://my.server.de
但是通过pyinstaller构建它并将其作为命令行工具运行它没有输出:
~/PycharmProjects/webctrl$ ./dist/wc_query_test/wc_query_test -h
~/PycharmProjects/webctrl$
如何修改wc_query_test.py以便它接受参数并充当命令行工具?
答案 0 :(得分:1)
感谢所有回复的人。在同事的帮助下,我得到了我的问题的答案。这是正常运行的代码:
<强> wc_query_test.py 强>:
import sys
import argparse
import getpass
def main(args):
if args['username'] is None:
print 'No user name specified. Login to WebCTRL needs a user name and password. Check all options for this command via -h'
sys.exit(1)
else:
username = args['username']
if args['password'] is None:
password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ')
else:
password = args['password']
if args['node'] is None:
print 'No path to a node specified. Check all options for this command via -h'
sys.exit(1)
if args['url'] is None:
print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de'
sys.exit(1)
else:
wsdlFile = args['url'] + '/_common/webservices/Eval?wsdl'
# This doesn't belong to my original code. It's rather for demonstration:
# Print the arguments and leave the script
print 'Username: ' + args['username']
print 'Node: ' + args['node']
print 'URL: ' + args['url']
# The parser is only called if this script is called as a script/executable (via command line) but not when imported by another script
if __name__=='__main__':
if len(sys.argv) < 2:
print "You haven't specified any arguments. Use -h to get more details on how to use this command."
sys.exit(1)
parser = argparse.ArgumentParser()
parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server')
parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server')
parser.add_argument('--node', '-n', type=str, default=None,
help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"')
parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de',
help="URL of the WebCTRL server as e.g. http://google.de")
args = parser.parse_args()
# Convert the argparse.Namespace to a dictionary: vars(args)
main(vars(args))
sys.exit(0)
现在,有三种方法可以执行wc_query_test,这是我想要实现的目标:
1)从命令行调用wc_query_test.py:
~/PycharmProjects/webctrl$ python wc_query_test.py -u aawrg -p wgAWER -n YWERGAEWR
2)从命令行编译并调用wc_query_test:
~/PycharmProjects/webctrl$ pyinstaller --distpath dist/. wc_query_test.py
~/PycharmProjects/webctrl$ ./dist/wc_query_test/wc_query_test -u aawrg -p wgAWER -n YWERGAEWR
3)从另一个python脚本调用wc_query_test,该脚本进入模块类型用法的方向:
import wc_query_test
myDictonary = {'username':'wsdl', 'password':'aaaaaa', 'node':'/trees/geographic', 'url':'https://my.server.de'}
wc_query_test.main(myDictonary)
所有三个版本都会产生与预期相同的输出,例如:
~/PycharmProjects/webctrl$ ./dist/wc_query_test/wc_query_test -u aawrg -p wgAWER -n YWERGAEWR
Username: aawrg
Node: YWERGAEWR
URL: https://webctrl.rz-berlin.mpg.de
答案 1 :(得分:0)
**kwargs
用于将字典或keyword=value
对传递给函数。 args = parser.parse_args()
返回argparse.Namespace
个对象,而不是字典。但是vars(args)
会从中生成一个字典。
In [2]: def foo1(args):
...: print(args)
...: print(args.foo)
...:
In [3]: def foo2(**kwargs):
...: print(kwargs)
...: print(kwargs['foo'])
In [12]: p = argparse.ArgumentParser()
In [13]: p.add_argument('--foo');
In [14]: args = p.parse_args('--foo one'.split())
In [15]: args
Out[15]: Namespace(foo='one')
将args
传递给foo1
:
In [16]: foo1(args)
Namespace(foo='one')
one
使用foo2
In [17]: foo2(args)
...
TypeError: foo2() takes 0 positional arguments but 1 was given
In [20]: foo2(**args)
TypeError: foo2() argument after ** must be a mapping, not Namespace
但传递扩展字典版本:
In [18]: vars(args)
Out[18]: {'foo': 'one'}
In [19]: foo2(**vars(args))
{'foo': 'one'}
one