简体   繁体   English

如何使用命令行参数调用python脚本?

[英]How to call a python script with command line args?

I have a script, client.py, that reads command line args straight as a script (not wrapped in a function like main()), like so: 我有一个脚本client.py,它直接以脚本形式读取命令行args(未包装在main()之类的函数中),如下所示:

opts, args = getopt.getopt(sys.argv[1:], "l:r:a:j:b:f:n:u:")

and prints a bunch of stuff. 并打印一堆东西。

I need to call this script from my code (on Google App Engine, if that matters). 我需要从我的代码中调用此脚本(如果需要的话,请在Google App Engine上)。 It seems that calling 似乎在打电话

import client

runs client.py as a script, but how do I specify the arguments? 将client.py作为脚本运行,但是如何指定参数?

You shouldn't do this unless you have to: if you have two Python scripts they can communicate in Python instead of through a command line parser. 除非必须这样做,否则不应该这样做:如果您有两个Python脚本,它们可以在Python中通信,而不是通过命令行解析器进行通信。 Rewrite client.py with an if __name__ == "__main__" check and then call its main function directly from your script. if __name__ == "__main__"检查重写client.py ,然后直接从脚本中调用其main函数。

If you don't have the option of doing that (and you should avoid this case if at all possible), you might be able to set sys.argv ; 如果您没有这样做的选择(并且尽可能避免这种情况),则可以设置sys.argv I'm not sure if GAE allows you to do that. 我不确定GAE是否允许您这样做。 YOu may also be able to use subprocess.Popen . 您可能还可以使用subprocess.Popen

You can't. 你不能 Use subprocess or os.exec*() , or modify the other script to use a main sentinel that parses the arguments then passes them to a main() function, then call main() yourself with the appropriate arguments. 使用subprocessos.exec*()或者修改其他脚本,以使用解析这些参数,然后将其传递到主哨main()函数,然后调用main()自己使用适当的参数。

Also, import client . 另外, import client

Google AppEngine uses a significantly modified version of Python and disables a lot of system and subprocess libraries as well as most C python modules. Google AppEngine使用经过重大修改的Python版本,并禁用了许多系统和子进程库以及大多数C python模块。 To call that script you'll need to import an entrypoint and call that. 要调用该脚本,您需要导入一个入口点并进行调用。 I believe on convention is to call your entrypoint main and call that, passing any args it might need. 我相信约定是调用您的入口点main并调用它,并传递可能需要的所有args。 This is a good practice in general. 通常,这是一个好习惯。 For example in the calling application: 例如在调用应用程序中:

from client import main
main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM