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])
Related
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.
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)
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])
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
I have 3 python files.(first.py, second.py, third.py) I'm executing 2nd python file from the 1st python file. 2nd python file uses the 'import' statement to make use of 3rd python file. This is what I'm doing.
This is my code.
first.py
import os
file_path = "folder\second.py"
os.system(file_path)
second.py
import third
...
(rest of the code)
third.py (which contains ReportLab code for generating PDF )
....
canvas.drawImage('xyz.jpg',0.2*inch, 7.65*inch, width=w*scale, height=h*scale)
....
when I'm executing this code, it gives error
IOError: Cannot open resource "xyz.jpg"
But when i execute second.py file directly by writing python second.py , everything works fine..!!
Even i tried this code,
file_path = "folder\second.py"
execfile(file_path)
But it gives this error,
ImportError: No module named third
But as i stated everything works fine if i directly execute the second.py file. !!
why this is happening? Is there any better idea for executing such a kind of nested python files?
Any idea or suggestions would be greatly appreciated.
I used this three files just to give the basic idea of my structure. You can consider this flow of execution as a single process. There are too many processes like this and each file contains thousandth lines of codes. That's why i can't change the whole code to be modularize which can be used by import statement. :-(
So the question is how to make a single python file which will take care of executing all the other processes. (If we are executing each process individually, everything works fine )
This should be easy if you do it the right way. There's a couple steps that you can follow to set it up.
Step 1: Set your files up to be run or imported
#!/usr/bin/env python
def main():
do_stuff()
if __name__ == '__main__':
The __name__ special variable will contain __main__ when invoked as a script, and the module name if imported. You can use that to provide a file that can be used either way.
Step 2: Make your subdirectory a package
If you add an empty file called __init__.py to folder, it becomes a package that you can import.
Step 3: Import and run your scripts
from folder import first, second, third
first.main()
second.main()
third.main()
The way you are doing thing is invalid.
You should: create a main application, and import 1,2,3.
In 1,2,3: You should define the things as your functions. Then call them from the main application.
IMHO: I don't need that you have much code to put into separate files, you just also put them into one file with function definitions and call them properly.
I second S.Lott: You really should rethink your design.
But just to provide an answer to your specific problem:
From what I can guess so far, you have second.py and third.py in folder, along with xyz.jpg. To make this work, you will have to change your working directory first. Try it in this way in first.py:
import os
....
os.chdir('folder')
execfile('second.py')
Try reading about the os module.
Future readers:
Pradyumna's answer from here solved Moin Ahmed's second issue for me:
import sys, change "sys.path" by appending the path during run
time,then import the module that will help
[i.e. sys.path.append(execfile's directory)]