732*_*72E 5 python import argparse
这个问题可能被认为是多余的,但为了我的辩护,我已经考虑过类似的问题并给出了解决方案,但它们对我不起作用(或者我只是不理解它们),正如我将展示的那样。
我想要做什么: 我写了几个 python 脚本,当使用 pyinstaller 构建时,每个脚本都是命令行工具(使用 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)
Run Code Online (Sandbox Code Playgroud)
正如我所说:从我的 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
Run Code Online (Sandbox Code Playgroud)
...从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
Run Code Online (Sandbox Code Playgroud)
来到实际问题: 我希望脚本 wc_query_test.py 成为一个模块,可以导入到另一个 python 脚本中并在那里执行,就像我在命令行中所做的那样传递参数。为了实现这一点,我在这个stackoverflow question 中遵循了@Waylan 的说明。
这是我想出的代码(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)
Run Code Online (Sandbox Code Playgroud)
...以及导入模块并调用它的脚本(test.py):
import wc_query_test
wc_query_test.main(username='wsdl', password='aaaaaa', node='/trees/geographic')
Run Code Online (Sandbox Code Playgroud)
当我在 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'
Run Code Online (Sandbox Code Playgroud)
运行 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)
Run Code Online (Sandbox Code Playgroud)
在 python 终端中运行它会产生预期的结果:
$ python test.py
Username: wsdl
Node: /trees/geographic
URL: https://my.server.de
Run Code Online (Sandbox Code Playgroud)
但是通过 pyinstaller 构建它并作为命令行工具运行它没有输出:
~/PycharmProjects/webctrl$ ./dist/wc_query_test/wc_query_test -h
~/PycharmProjects/webctrl$
Run Code Online (Sandbox Code Playgroud)
如何修改 wc_query_test.py 以便它接受参数并用作命令行工具?
感谢大家的回应。在一位同事的帮助下,我得到了问题的答案。这是功能代码:
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)
Run Code Online (Sandbox Code Playgroud)
现在,有三种执行 wc_query_test 的方法,这就是我想要实现的目标:
1)从命令行调用wc_query_test.py:
~/PycharmProjects/webctrl$ python wc_query_test.py -u aawrg -p wgAWER -n YWERGAEWR
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
所有三个版本都会产生与预期相同的输出,例如:
~/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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4268 次 |
| 最近记录: |