I would like to implement something like "python3 project.py - function", and only the content that was in the function was issued?

def func(): print("Hello, World!") def func2(): print("World, Hello!") 

And then

 $ python3 файл.py *колдовство, обращение только к функции func2* 

The conclusion was:

 World, Hello! 
  • You can pass arguments to the script from the command line and, depending on the arguments, change the behavior of the script - nörbörnën
  • Run a script like python3 from the command line -c 'import file; func2 () ' ? - 0andriy

2 answers 2

If you have a module module defined in the module.py file located in one of the sys.path directories (the current directory is included in the pythonpath for -c ), then to call the function from this module:

 $ python -c 'import module; module.function()' 

    I propose this solution:

     import sys
    
     def func ():
         print ("Hello, World!")
    
     def func2 ():
         print ("World, Hello!")
    
     name = sys.argv [1]
     f = globals (). get (name)
     if f:
         f ()
    

    Example of use:

      $ python file.py func 

    If there is no function with the specified name, the script will output nothing. You can modify it to display the error:

     if f:
         f ()
     else:
         print ('No such method:% s'% name)