Home > Enterprise >  Running one python script from another script with command line argument having executable in it
Running one python script from another script with command line argument having executable in it

Time:12-01

I am trying to run a python script within another python script. Which will run 10 times and produce 10 outputs.

I want to run program1.py inside program2.py. Now my program1.py was initially taking a C executable inside it and it takes 1 command line argument.

The program1.py looks like below:

import os
import sys
dataset = sys.argv[1]

os.system(f"/home/Dev/c4.5 -u -f {dataset}")
os.system(f"/home/Dev/c4.5rules -u -f {dataset}")
os.system(f"/home/Dev/c4.5rules -u -f {dataset} > Temp")

f = open('Temp')
# Some code

Where c4.5 and c4.5rules are the name of the executable files. To run this I was using python3 program1.py dataset_name

Now I am trying to put this program1.py inside program2.py and I am trying this below approach:

import os
import subprocess

# Some code
for track in range(0, 10):
    with open(f'Train_{track}', 'r') as firstfile, open(f'DF_{track}.data', 'w') as secondfile:
        for line in firstfile:
            secondfile.write(line)
    os.system("/home/Dev/program1.py DF_track")
    #subprocess.Popen("/home/Dev/program1.py DF_track", shell=True) 

Where I simply want to get the output of program1.py 10 times and want to use DF_track as the command line input for each output generation.

Using above approach I am getting lots of error. Please help.

Edit_1 :

Actually whenever I am trying to run, my cursor is not working, it is freezing, so unable to copy the errors.

Here are some of them :

1. attempt to perform an operation not allowed by security policy.
2. syntax error : word expected (expecting ")")

CodePudding user response:

Imagine I have 2 files, the first file is a.py and the other is b.py and I want to call the a.py from b.py.

The content of a.py is:

print('this is the a.py file')

and the content of b.py is:


import os

stream = os.popen('python3 a.py')
output = stream.read()

print(output)

Now when I call b.py from terminal I get the output I expect which is a.py print statment


user@mos ~ % python3 b.py
this is the a.py file

You can do this with subprocess too instead of os module.

Here is a nice blog I found online where I got the code from: https://janakiev.com/blog/python-shell-commands/

CodePudding user response:

See the example below.

a.py

def do_something():
  pass

b.py

from a import do_something

do_something()
  • Related