简体   繁体   中英

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:

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). It seems that calling

import client

runs client.py as a script, but how do I specify the arguments?

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. Rewrite client.py with an if __name__ == "__main__" check and then call its main function directly from your script.

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 ; I'm not sure if GAE allows you to do that. YOu may also be able to use 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.

Also, 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. 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. This is a good practice in general. For example in the calling application:

from client import main
main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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