Скрипт внутри скрипта python

Запустите скрипт Python из другого скрипта Python, передав аргументы [duplicate]

Я хочу запустить Python script из другого Python script. Я хочу передать переменные, как я бы использовал в командной строке. Например, я бы запускал свой первый script, который перебирал бы список значений (0,1,2,3) и передавал их во второй script script2.py 0 , затем script2.py 1 и т.д. Я нашел SO 1186789, который является аналогичным вопросом, но ars отвечает на вызовы функции, где, поскольку я хочу запустить целую script не только функцию, а вызов balpha вызывает script, но без аргументов. Я изменил это на что-то вроде ниже в качестве теста:

Но он не принимает правильные значения. Когда я печатаю sys.argv в файле script2.py, это первоначальный командный вызов с первым script «[‘C:\script1.py’]. Я не хочу менять исходный script (т.е. script2.py в моем примере), так как я его не владею. Я полагаю, что должен быть способ сделать это, я просто смущен, как вы это делаете.

Вопрос в том, знаете ли вы имя скрипта (затем импортируете его) или если вы не знаете имя скрипта во время программирования (тогда используйте subprocess.call). Во втором случае этот вопрос также не будет дубликатом. Поскольку вопрос не проясняет, он также не очень хороший.

@Trilarion: Триларион: неправильно. Вы можете импортировать модуль Python, даже если его имя генерируется во время выполнения.

Читайте также:  Light background html colors

@J.F.SebastianХорошо. В качестве дополнительного замечания: этот способ не очень хорошо описан ни в одном ответе здесь или в связанном вопросе, за исключением частично в stackoverflow.com/a/1186840/1536976 .

@Trilarion: почему это должно быть покрыто вообще? Имена зафиксированы в обоих вопросах. В любом случае, выражение «если вы не знаете имя скрипта во время программирования (тогда используйте subprocess.call)». не так, независимо. Если у вас есть новый вопрос; спроси

@J.F.SebastianСогласен снова. У меня нет вопросов прямо сейчас. Если я приду с одним, я обязательно спрошу.

@Oli4 Oli4 «определенно» — сильное слово. Хотите разработать? Я вижу решение subprocess.call (), которое принимает несколько аргументов командной строки. Я вижу, что import упоминается для случаев, когда определена функция main () (это не поможет OP, но это правильный путь для многих других людей с подобной проблемой). Я вижу execfile () для Python 2, который использует все, что вы положили в sys.argv (правда, последний бит не упоминается явно) — эта опция должна игнорироваться новичками. Существует даже явный ответ os.system () с несколькими аргументами (ответ, который принимается здесь).

@J.F.SebastianПосле вашей разработки, я склонен согласиться с вами. Хотя в другом вопросе явно не указано, как отправлять аргументы или что это требуется, вопросы действительно похожи. Иногда, задавая вопрос по-разному, появляются разные решения, так как ответ ChrisAdams решил мою проблему. Я прошу прощения за мое предыдущее заявление о том, что это действительно не дубликат, и спасибо.

Источник

Run Python script from another script & pass arguments

In Python programming we often have multiple scripts with multiple functions. What if, if some important and repeated function is in another script and we need to import and run to our main script. So, here in this article we will learn about several methods using which you can Run a Python script from another Python script and pass arguments.

Table Of Contents

Method 1 : Importing in other script

First method we will be using is very simple and easiest one. In this method we can just import the function and then call the function by just passing the arguments. Must keep in mind that both the files should reside in the same folder.

See the example code below

Frequently Asked:

# *args has been used to pass variable number of positional arguments. def expenseCalculator(*expense): # sum adds the numbers provided as parameters. print('Previous month expense was ',sum(expense))
# importing the function from another module. from code_1 import expenseCalculator # calling the function and by passing arguments. expenseCalculator(2000,3000)
Previous month expense was 5000

So, In the above code and output you can see we have two files code_1.py and script.py. In code_1.py we have a function which takes positional arguments and returns the sum by using the sum() method. This function has been imported in the script.py. When this function is called in the script.py by providing some arguments, the function executes and returns the sum of the arguments provided.

Method 2 : Using os.system and sys.argv

Next method we can use to Run a Python script from another Python script and pass arguments is a combination of two methods first is system() of os module and another is argv() from sys module. Let’s look both of these methods one by one.

os.system : os module comes bundled with python programming language and is used to interact with system or give system commands to our Operating System. system() method is used to execute system commands in a subshell.

sys.argv : This module in python programming language is widely used to interact with the system it provides various function and modules that can communicate with the Python Interpreter and also used to manipulate python runtime environment. sys.argv reads the arguments which are passed to the Python at the time of execution of the code. Arguments provided to the sys.argv is stored in list, first index which is index number 0 is reserved for the file name and then arguments are stored.

Now see the example code below and then we will discuss more about this method.

# importing sys module import sys # *args has been used to pass variable number of positional arguments. def expenseCalculator(*expense): # sum adds the numbers provided as parameters. print('Previous month expense was ',sum(expense)) # storing the arguments by slicing out the 0 index which holds the file name. arguments = sys.argv[1:] # initialized an empty list. expenses = [] # looping through the arguments to convert it into int. for i in arguments: expenses.append(int(i)) # calling the function and passing the expenses. expenseCalculator(*expenses)
# importing the os module. import os # running the file code_1.py and passing some arguments. os.system("python3 code_1.py 2000 3000 5000")
Previous month expense was 10000

So, In the code and output above you can see we have two files code_1.py which has function expenseCalculator() which takes the variable number of positional arguments and returns the sum of all the expenses using the sum() function. Also we have sys.argv() file which reads all the arguments which are provided at the time of execution and then using int() function we have converted the arguments which are in string to integer.

Then there is script.py from where we are running another script which is code_1.py. In this file, we have used os.system() to run the code_1.py and also provided some arguments.

So, you can see we have used sys.argv() to read all the arguments which are passed at the time of execution and used os.system() to execute the program with some arguments.

Method 3 : Using subprocess module

Another method we can use to Run a Python script from another Python script and pass arguments is a combination of Popen() and argv() methods.

The Popen() method is of subprocess module which comes pre-installed with Python programming language and is mostly used to execute system commands. It has some features which provide edge over the os module like, this connects to input/output/error pipes and obtains their return codes. This also allows spawning new process. The Popen() method is used to execute system commands via string arguments/commands.

Now See the Example codes below

# importing sys module import sys # *args has been used to pass variable number of positional arguments. def expenseCalculator(*expense): # sum adds the numbers provided as parameters. print('Previous month expense was ',sum(expense)) # storing the arguments by slicing out the 0 index which holds the file name. arguments = sys.argv[1:] # initialized an empty list. expenses = [] # looping throught the arguments to convert it into int. for i in arguments: expenses.append(int(i)) # calling the function and passing the expenses. expenseCalculator(*expenses)
# importing subprocess module import subprocess # using Popen() method to execute with some arguments. subprocess.Popen("python3 code_1.py 2000 3000 4000",shell=True)
Previous month expense was 9000

So, In the code and output above you can see we have used Popen() method to run a python script and argv() to read arguments. The code_1.py file is same as the method 2 but in script.py file instead of system() we have used Popen() to pass arguments. The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.

SUMMARY

So In this Python tutorial article we learned about several methods using which we can Run a Python script from another Python script and pass arguments. We learned about sys.argv() using which which we can read the arguments passed at the time of execution in the command prompt. Also we learned about two other methods Popen() of subprocess module and system() of os module using which we can execute the system commands or here we have used to run the Python script from another Python script and also passed some arguments at the time of execution.

You can always use any of the methods above, but most easy to understand and implement is the first method. Make sure to read and write example codes in order to have a better understanding of this problem.

Источник

Как запустить файл со скриптом из другого файла со скриптом, запускающим первый файл?

Всем привет. Кто-нибудь знает способы запуска скрипта на python, который, к примеру, находится в файле file_1.py путем запуска другого файла file_2.py с кодом для запуска file_1.py. Для пояснения скажу, что в file_1.py находиться бесконечный цикл, который записывает данные в файл, поэтому простым импортом тут не обойтись, так как код в file_2.py должен интерпретироваться дальше после запуска file_1.py.

Viktor_T2

import subprocess cmd = 'python script.py' p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) out, err = p.communicate() result = out.split('\n') for lin in result: if not lin.startswith('#'): print(lin)

samodurOFF

Привет! Как я понял тебе нужно инжектировать\импортировать код после выполнения первого скрипта. Import можно вызывать и в конце скрипт, и даже используя условия. Вот пример:

import_rand = False if import_rand: import random print(int(random.randrange(10))) elif not import_rand: print(int(random.randrange(10)))

Если True, то модуль random импортируется и выведется число, если False, то будет ошибка (Модуль random не найден).

samodurOFF

Если честно, то я не понял как ваше решение подходит в моем случае. Поясню еще. Код в file_2.py использует данные из файла, который был создан через file_1.py. Этот файл, пусть он будет назваться data.csv, постоянно пополняется новыми данными, которые постоянно обрабатываются в file_2.py циклом. Поэтому, как мне кажется, код в file_2.py должен выглядеть примерно так:

import pandas as pd # ТРИГЕР для запуска кода в file_1.py, чтобы получить файл data.csv while True: df = pd.read_csv('data.csv') print(df.tail())

Так вот, мне и нужно понять, как реализовать этот ТРИГЕР

Данил Самодуров, Снова здравствуйте. Создайте в file_1 функцию, например gen_file потом импортируйте ее в file_2 при помощи from file_1 import gen_file. После этого вы можете вызывать когда вам нужно функцию внутри другого фала, также передавать ему атрибуты через эту функцию и получать ответ через return (если нужно). Если вы не знаете как работать с функциями, то вот простой пример —

def gen_file(const_one, const_two): print("<> <>".format(str(const_one), str(const_two)))
from file_1 import gen_file a = "Это константа 1" b = "А это константа 2" gen_file(a, b)

Это константа 1 А это константа 2

samodurOFF

koval01, я знаю как работать с функциями. file_1.py уже и так содержит функцию и я ее импортировал в file_2.py. Это первое что пришло мне в голову. Но, как вы поняли, это не сработало. Проблема в том, что функция в file_1.py сдержит бесконечный цикл и ничего не возвращается через return. При ее вызове через импорт в file_2.py код ниже места вызова исполняться не будет, так как интерпретатор будет ожидать завершение работы скрипта в file_1.py а этого не происходит.

Источник

Оцените статью