K
K
kolomiec_artiom2018-06-23 17:36:09
Python
kolomiec_artiom, 2018-06-23 17:36:09

How to import a module by storing its name in a variable?

Good evening friends!
I run the .py file through the command console:
main.py read.py write.py
The first parameter is the main program, 2 and 3 are the modules that should be loaded in the main program.
I catch them with the help of sys.argv
And how do I import them further? import sys.argv[1] is not suitable

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Gornostaev, 2018-06-23
@kolomiec_artiom

for module in sys.argv[1:]
    __import__(module)

A
Alexander Zelenin, 2014-10-06
@nepster-web

$dateTime = DateTime::createFromFormat('Y-m-d H:i:s','2014-10-06 14:01:25');
$formatter = new IntlDateFormatter('ru_RU', IntlDateFormatter::FULL, IntlDateFormatter::FULL);
$formatter->setPattern('d MMMM Y, k:mm:ss');
echo $formatter->format($dateTime);

A
Alexander Taratin, 2014-10-06
@Taraflex

Terrible code found on the net

function rdate($format, $timestamp = null, $case = 0)
{
 if ( $timestamp === null )
  $timestamp = time();

 static $loc =
  'Январ,ь,я,е,ю,ём,е
  Феврал,ь,я,е,ю,ём,е
  Март, ,а,е,у,ом,е
  Апрел,ь,я,е,ю,ем,е
  Ма,й,я,е,ю,ем,е
  Июн,ь,я,е,ю,ем,е
  Июл,ь,я,е,ю,ем,е
  Август, ,а,е,у,ом,е
  Сентябр,ь,я,е,ю,ём,е
  Октябр,ь,я,е,ю,ём,е
  Ноябр,ь,я,е,ю,ём,е
  Декабр,ь,я,е,ю,ём,е';

 if ( is_string($loc) )
 {
  $months = array_map('trim', explode("\n", $loc));
  $loc = array();
  foreach($months as $monthLocale)
  {
   $cases = explode(',', $monthLocale);
   $base = array_shift($cases);
   
   $cases = array_map('trim', $cases);
   
   $loc[] = array(
    'base' => $base,
    'cases' => $cases,
   );
  }
 }
 
 $m = (int)date('n', $timestamp)-1;
 
 $F = $loc[$m]['base'].$loc[$m]['cases'][$case];

 $format = strtr($format, array(
  'F' => $F,
  'M' => substr($F, 0, 3),
 ));
 
 return date($format, $timestamp);
}

$t = strtotime("2014-10-06 14:01:25");
echo rdate("j F Y года, H:i",$t,1);

A
Andrey Ezhgurov, 2014-10-06
@eandr_67

The matter is that in PHP there are no Russian names of months. So you still have to shape it by hand. But for cutting there is getdate. Something like this:

$month=[1=>'января', ..., 12=>'декабря'];
$test_date='2014-10-06 14:01:25';
$tmp=getdate(strtotime($test_date));
$result=sprintf('%02d %s %4d года, %02d:%02d',
                $tmp['mday'], $month[$tmp['mon']], $tmp['year'], $tmp['hours'], $tmp['minutes']);

Another option is based on generating a month in any form, and then changing it regularly. Something like:
$result=preg_replace_callback('#<(\d+)>#', function($data){
  static $month=[1=>'января', ..., 12=>'декабря'];
  return $month[$data[1]];
}, date('d <m> Y года, H:i', strtotime($test_date)));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question