简体   繁体   中英

Executing a Python Script From Python Shell

I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py.

I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter the Python shell. My goal is to be able to execute the python script amazon.py within this shell. What command should I be using to execute amazon.py?

Normally, you just import the file and call a function within it:

import APP.amazon
APP.amazon.main() 

This would only work if amazon.py is laid out like this:

def main():
    ...code...

if __name__ == '__main__':
    main()

Also, in the directory ~/PROJECT/APP there needs to exist a file __init__.py with nothing in it, or else Python won't see APP as a package with the module amazon in it.

Disclaimer: I don't actually know what manage.py does.

Normally a script is "executed" upon import. I'd suggest you wrap your functionality in amazon.py in a function:

def call_functionality():
    ...

In your shell you can now import it with:

import path.to.amazon as amazon

and then execute it by

amazon.call_functionality()

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