Make a python script that opens another python script - python

I am very disappointed that after looking for several hours, I have still not found an answer to: - Make a python script that opens another python script ?
Mabye I don't know how to search for stuff, but I am usually good at finding solutions online.
Any help would be gladly appreciated!
Here's my code:
import subprocess
subprocess.Popen(['C:\Users\user\Documents\run.py'])
Here is the python file called "run.py"
print('Hello World!')
Thanks!

You can use the call library, it's pretty easy:
from subprocess import call
call(["python", "your_file.py"])

This is how I will go about it. Suppose you have two files: Main.py and run.py
and will want Main.py to open and run this file run.py:
this is the content of Main.py : it calls run.py through import (run.py file needs to be in the same folder)
import run
this is your run.py
print('Hello World!')
Then you can run Main.py by calling python Main.py
the output will be : Hello World!
Let me know if it works.

Try this:
your_cmd = "python3 path/to/file/run.py"
p = subprocess.Popen("exec " + your_cmd, stdout=subprocess.PIPE, shell=True)

i find this to work and it looks clearer:
import subprocess
import pathlib
path_to_file=pathlib.Path(__file__).parent.resolve()
script_path=f'{path_to_file}/your_script.py'
subprocess.run(['python',script_path])

Related

Issue with using os.system to call another script

I am working on another issue which requires me to use os.system() to call another python script. I know that subprocess is the better solution but for what I'm trying to do but I can't use that and am stuck with os.system(). I set up a small test program as follows to try and figure out os.system():
sript1.py
import os
import sys
os.system("C:/Users/user/Documents/code/test/called_script.py")
called_script.py
import os
import sys
sourceFile = open('C:/Users/user/Documents/code/test/test.txt', 'w')
print("hi", file = sourceFile)
sourceFile.close()
If I run script1.py it will not create (or if it already exists write to) test.txt
But if I run called_script.py directly it will create/write to the file test.txt
I'm sure I'm overlooking something simple, but could someone help me out with why running script1.py is not getting me the desired outcome?
Thanks to the above comments, the solution is that script1.py should read
os.system("py C:/Users/user/Documents/code/test/called_script.py")
Because Windows does not know what to do with a .py file otherwise.

Is there a way to import a variable in python without looping code?

I have looked at multiple different questions and answers but nothing I have looked at is helping me in the slightest. I am using Python 3 for all of this.
I am having a bit of trouble using python to transfer a variable to be used in a command-line prompt through python code. I am using os.system, and would prefer to use this, to execute a second python file, in the same folder.
The opening through command prompt works after a bit of testing, but when I try to import a variable from the first python code, it loops through the entire first bit of code.
My first python code is as follows:
import os
variable_to_transfer=input()
os.system('cmd /c "python file2.py"')
My second python code is as follows:
import os
from file1.py import variable_to_transfer
command='cmd /k "ping {0}"'.format(variable_to_transfer)
os.system(command)
When I run this set of code it runs through the first code once, goes to the second code and doesn't do anything at the line
from file1.py import variable_to_transfer
I intend for my codes to transfer the variable but it just loops. Any way to fix this?
It loops because your file1 is calling your file2 which imports from your file1 and recall your file2, etc. over and over. What you should do instead, is pass the variable as an argument and retrieve it from there. For example:
# file1.py
import os
variable_to_transfer=input()
os.system('cmd /c "python file2.py %s"' % variable_to_transfer)
# file2.py
import os
import sys
command='cmd /k "ping {0}"'.format(sys.argv[1])
os.system(command)

How to execute one python script in a different directory with another script?

I am trying to execute one python script (file2.py) through the other (file1.py).
The first file is located in test/file1.py and the second file in test/test1/file2.py.
As an example file2.py has the following code:
file = open("textfile.txt","w")
file.write("Hello world")
file.close()
so I am trying to create a .txt file from file1.py.
To do so, I have tried several solutions such as:
import Test1.file2
or
import os
os.system('Test1/file2.py')
or
from subprocess import call
call('Test1/file2.py', shell='True')
in file1.py but none of them seem to work. The first solution works well if I want to import a function but it does not work when I want to create a text file.
Does anyone know what I am doing wrong and how to fix it?
To run the other file, you have some options:
The best one is to treat the file as a module, import it, and call it's methods, so you would have to encapsulate the .txt creating inside a method
#on file1.py
def createTxt():
#your txt creation goes here
and call createTxt from file2.py importing file1.py, which will run the method and create the txt file
#on file2.py
import file1
createTxt()
You can also use execfile('file2.py') to execute it and run it as a script or make a system call with os.system('python file2.py') importing os to also run as a script
The first one is safer and a better code in general, avoid using the other two when possible

How to include py file based on the command line input?

My python script has to include other python scripts in the code. And I want the other scripts to be passed as command line arguments.
For example:
My script is test.py, and I want to include first.py in my code based on the command line input.
Command line input
python test.py first.py
In the code I want first.py to be imported as in:
import first
But I can't figure out a way. I tried using optparse and fileInput, but they didn't turn out to be what I had intended.
I don't think it is best practice to import module from arguments, but if you really want to do that, could try below code:
import sys
for file_name in sys.argv[1:]:
module_name = file_name.replace('.py', '')
exec('import %s' % module_name)
I don't know the best way to answer your question. But here is my solution. Again, this may not be the best solution-
module_name = input()
with open('file_name.py', 'w') as py_file:
py_file.write('import ' + module_name)
Why doesn't a simple import statement in the original code do the job? Like so:
import first
#
# The rest of the program.
#
Then from the command line, you only need to run
python test.py
As long as test.py and first.py are in the same directory, this approach is effectively "including" first.py in test.py. Please include more information about why you want to pass first.py as a command line argument. It seems to me, since you already know what your program will be doing with first.py, and you have to write your code under the assumption that first.py will be imported anyway, you might as well just do it at the beginning of test.py.
python test.py first.py - In this case, test.py is argv[0] and first.py is argv[1]
Add below code in your test.py
from sys import argv
execfile(argv[1])

Run python file inside another

I am using python 3.5
I want to run a python script calling from another python script.
In particular, say I have script A (in particular, this is the exact file that I want to run: script A file):
Script A is the following.
if __name__ == '__main__':
args = argparser.parse_args()
_main(args)
I am running script B, inside script B, it calls script A.
How do I simply do this by calling the main function of script A while running script B?
Please no os.system('python scriptA.py 1'), this is not what i want. thanks
normally you can import it and call the main function
like
import script_a
...
script_a._main()
of course it could be that the script_a is not in you src structure, so that you can not simple import, or script_a is completely somewhere else.
Suppose the path of the script_a is path_a
you can
import sys
sys.path.append(path_a)
import script_a
script_a._main()
if you want to pass the args to script_a , in your script_b
import script_a
...
if __name__ == '__main__':
args = argparser.parse_args()
script_a._main(args)
In Script B simply import Script A,
import script_A
or
from script_A import *
now you can access your script A in script B
Treat the file like a module and put import scriptA at the top of your file.
You can then use scriptA.main(1) where 1 is the argument you are passing to it.
N.B When importing do not put .py at the end.
If you have code which is not indented inside of script A and if you import script A inside script B, it will automatically first run script A and then move on to the __main__() of script B. How ever if you wish control when the execution of script A begins, then , indent your code in Script A or code it in a normal function such as def start() .
Now, import Script A into Script B as follows
import ScriptA
And run the script A as
ScriptA.start()
NOTE: Make sure that script A and script B are in the same directory for this to work. Hope this solves your purpose. Cheers!

Categories