Python - how do I call external python programs?

前端 未结 4 1600
轮回少年
轮回少年 2020-12-17 08:45

I\'ll preface this by saying it\'s a homework assignment. I don\'t want code written out for me, just to be pointed in the right direction.

相关标签:
4条回答
  • 2020-12-17 08:50

    Also if you need to pass additional arguments do this:

    import subprocess
    subprocess.call(["python", "myscript.py", "arg1", "arg2", "argN"])
    
    0 讨论(0)
  • 2020-12-17 08:53

    Check out the subprocess documentation.

    0 讨论(0)
  • 2020-12-17 09:03

    If you want to load an external Python file and run it inside the current interpreter without the burden to dealing with modules, you can use the standard importlib.util module.

    This is useful when you need to ship some Python scripts for demonstration purposes, but you don't want to make them part of a (sub-)module--while still being able to run them automatically, like during integration testing. Here is an example:

    # A sample Python script
    sh$ cat snippet/demo.py 
    SOME_MODULE_GLOBAL=True
    print("Hello, here is the demo snippet!")
    # There is no `__init__.py in the _snippet_ directory
    sh$ cat snippet/__init__.py
    cat: snippet/__init__.py: No such file or directory
    

    Now using importlib.util you can load demo.py even if it is not part of a module:

    >>> import importlib.util
    
    # Bypass the standard import machinery to manually load a Python script from
    # a filepath
    >>> spec = importlib.util.spec_from_file_location('demo','snippet/demo.py')
    >>> spec
    ModuleSpec(name='demo', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fa549344eb8>, origin='snippet/demo.py')
    >>> module = importlib.util.module_from_spec(spec)
    >>> module
    <module 'demo' from 'snippet/demo.py'>
    
    # The next command will run the module:
    >>> spec.loader.exec_module(module)
    Hello, here is the demo snippet!
    
    # Module variables are accessible just like if it was a
    # _normally_ imported module:
    >>> module.SOME_MODULE_GLOBAL
    True
    
    0 讨论(0)
  • 2020-12-17 09:14

    If you want to call each as a Python script, you can do

    import subprocess
    subprocess.call(["python", "myscript.py"])
    subprocess.call(["python", "myscript2.py"])
    

    But a better way is to call functions you've written in other scripts, like this:

    import myscript
    import myscript2
    
    myscript.function_from_script1()
    myscript2.function_from_script2()
    

    Where function_from_script1() etc are defined in the myscript.py and myscript2.py files. See this page on modules for more information.

    0 讨论(0)
提交回复
热议问题