# PHP program to generate a random number in a given range (min, max)

| | |
Using the rand() function: The rand() function generates a pseudo-random number between a given range, or between 0 and the default maximum (getgrandmax()), which is system dependent.Syntax:
`int rand (\$min, \$max) `
Parameters:the rand() function takes two optional parameters as above and described below.
• \$min: is an optional parameter used to set the lower limit for the random number. The default min is 0.
• \$max:This is an optional parameter used to set an upper limit for the random number. The default is max - this is the return value of getgrandmax(), which is system dependent (for Windows it is 32767).
Program 1:PHP program to generate a random number using the rand function().``` // PHP program for generating a random number // within the specified range // Generate random numbers without a range // the rand() function returns a random number \$num1 = rand(); echo " Random number: " . \$num1 . "" ; // Generate random numbers in a given range \$num2 = rand (7, 100); echo "Random number in range (7, 100):" , \$num2 ; ?> Exit:Random number: 77551982 Random number in range (7, 100): 37 Note.The rand() function - it is a pseudo-random function which means that it takes a seed from the machine and generates a number according to it. Thus, the method for generating numbers is not completely random. This can be tracked to a certain extent. So it is not cryptographically secure. It is not used for cryptography where randomization is very important. Use the random_int() function to generate a cryptographically secure random number. Using the random_int() function: random_int() is used to generate cryptographically secure random numbers. These numbers can be used for objective results. CryptGenRandom() function on Windows and getrandom (2) system call on Linux to generate a random number.Syntax:int random_int (\$min, \$max) Parameters:The random_int() function takes two parameters as above and described below. \$min: contains the lower limit of the random number. \$max:contains the upper limit of the random number. Program 2: Generate random numbers in a range using the random_int() function. // PHP program for generating a random number // in a given range // Generate random numbers in a given range // using the random_int() function \$num1 = random_int (35 , 100); echo " Random number in range (35, 100): " . \$num1 . "" ; // Random number in the range (10, 30) \$num2 = random_int (10, 30); echo " Random number in range (10, 30): " . \$num2 ; ?> Exit:Random number in range (35, 100): 93 Random number in range (10, 30): 28 PHP program to generate a random number in a given range (min, max): StackOverflow Questions Meaning of @classmethod and @staticmethod for beginner? Question by user1632861 Could someone explain to me the meaning of @classmethod and @staticmethod in python? I need to know the difference and the meaning. As far as I understand, @classmethod tells a class that it"s a method which should be inherited into subclasses, or... something. However, what"s the point of that? Why not just define the class method without adding @classmethod or @staticmethod or any @ definitions? tl;dr: when should I use them, why should I use them, and how should I use them? Answer #1: Though classmethod and staticmethod are quite similar, there"s a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all. Example class Date(object): def __init__(self, day=0, month=0, year=0): self.day = day self.month = month self.year = year @classmethod def from_string(cls, date_as_string): day, month, year = map(int, date_as_string.split("-")) date1 = cls(day, month, year) return date1 @staticmethod def is_date_valid(date_as_string): day, month, year = map(int, date_as_string.split("-")) return day <= 31 and month <= 12 and year <= 3999 date2 = Date.from_string("11-09-2012") is_date = Date.is_date_valid("11-09-2012") Explanation Let"s assume an example of a class, dealing with date information (this will be our boilerplate): class Date(object): def __init__(self, day=0, month=0, year=0): self.day = day self.month = month self.year = year This class obviously could be used to store information about certain dates (without timezone information; let"s assume all dates are presented in UTC). Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typical instancemethod, having the first non-optional argument (self) that holds a reference to a newly created instance. Class Method We have some tasks that can be nicely done using classmethods. Let"s assume that we want to create a lot of Date class instances having date information coming from an outer source encoded as a string with format "dd-mm-yyyy". Suppose we have to do this in different places in the source code of our project. So what we must do here is: Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable. Instantiate Date by passing those values to the initialization call. This will look like: day, month, year = map(int, string_date.split("-")) date1 = Date(day, month, year) For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use classmethod. Let"s create another "constructor". @classmethod def from_string(cls, date_as_string): day, month, year = map(int, date_as_string.split("-")) date1 = cls(day, month, year) return date1 date2 = Date.from_string("11-09-2012") Let"s look more carefully at the above implementation, and review what advantages we have here: We"ve implemented date string parsing in one place and it"s reusable now. Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better). cls is an object that holds the class itself, not an instance of the class. It"s pretty cool because if we inherit our Date class, all children will have from_string defined also. Static method What about staticmethod? It"s pretty similar to classmethod but doesn"t take any obligatory parameters (like a class method or instance method does). Let"s look at the next use case. We have a date string that we want to validate somehow. This task is also logically bound to the Date class we"ve used so far, but doesn"t require instantiation of it. Here is where staticmethod can be useful. Let"s look at the next piece of code: @staticmethod def is_date_valid(date_as_string): day, month, year = map(int, date_as_string.split("-")) return day <= 31 and month <= 12 and year <= 3999 # usage: is_date = Date.is_date_valid("11-09-2012") So, as we can see from usage of staticmethod, we don"t have any access to what the class is---it"s basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does. Answer #2: Rostyslav Dzinko"s answer is very appropriate. I thought I could highlight one other reason you should choose @classmethod over @staticmethod when you are creating an additional constructor. In the example above, Rostyslav used the @classmethod from_string as a Factory to create Date objects from otherwise unacceptable parameters. The same can be done with @staticmethod as is shown in the code below: class Date: def __init__(self, month, day, year): self.month = month self.day = day self.year = year def display(self): return "{0}-{1}-{2}".format(self.month, self.day, self.year) @staticmethod def millenium(month, day): return Date(month, day, 2000) new_year = Date(1, 1, 2013) # Creates a new Date object millenium_new_year = Date.millenium(1, 1) # also creates a Date object. # Proof: new_year.display() # "1-1-2013" millenium_new_year.display() # "1-1-2000" isinstance(new_year, Date) # True isinstance(millenium_new_year, Date) # True Thus both new_year and millenium_new_year are instances of the Date class. But, if you observe closely, the Factory process is hard-coded to create Date objects no matter what. What this means is that even if the Date class is subclassed, the subclasses will still create plain Date objects (without any properties of the subclass). See that in the example below: class DateTime(Date): def display(self): return "{0}-{1}-{2} - 00:00:00PM".format(self.month, self.day, self.year) datetime1 = DateTime(10, 10, 1990) datetime2 = DateTime.millenium(10, 10) isinstance(datetime1, DateTime) # True isinstance(datetime2, DateTime) # False datetime1.display() # returns "10-10-1990 - 00:00:00PM" datetime2.display() # returns "10-10-2000" because it"s not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details. datetime2 is not an instance of DateTime? WTF? Well, that"s because of the @staticmethod decorator used. In most cases, this is undesired. If what you want is a Factory method that is aware of the class that called it, then @classmethod is what you need. Rewriting Date.millenium as (that"s the only part of the above code that changes): @classmethod def millenium(cls, month, day): return cls(month, day, 2000) ensures that the class is not hard-coded but rather learnt. cls can be any subclass. The resulting object will rightly be an instance of cls. Let"s test that out: datetime1 = DateTime(10, 10, 1990) datetime2 = DateTime.millenium(10, 10) isinstance(datetime1, DateTime) # True isinstance(datetime2, DateTime) # True datetime1.display() # "10-10-1990 - 00:00:00PM" datetime2.display() # "10-10-2000 - 00:00:00PM" The reason is, as you know by now, that @classmethod was used instead of @staticmethod Answer #3: @classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance. @staticmethod means: when this method is called, we don"t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can"t access the instance of that class (this is useful when your method does not use the instance). What is the meaning of single and double underscore before an object name? Can someone please explain the exact meaning of having single and double leading underscores before an object"s name in Python, and the difference between both? Also, does that meaning stay the same regardless of whether the object in question is a variable, a function, a method, etc.? Answer #1: Single Underscore Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself. To quote PEP-8: _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore. Double Underscore (Name Mangling) From the Python docs: Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes. And a warning from the same page: Name mangling is intended to give classes an easy way to define ‚Äúprivate‚Äù instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private. Example >>> class MyClass(): ... def __init__(self): ... self.__superprivate = "Hello" ... self._semiprivate = ", world!" ... >>> mc = MyClass() >>> print mc.__superprivate Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: myClass instance has no attribute "__superprivate" >>> print mc._semiprivate , world! >>> print mc.__dict__ {"_MyClass__superprivate": "Hello", "_semiprivate": ", world!"} Answer #2: __foo__: this is just a convention, a way for the Python system to use names that won"t conflict with user names. _foo: this is just a convention, a way for the programmer to indicate that the variable is private (whatever that means in Python). __foo: this has real meaning: the interpreter replaces this name with _classname__foo as a way to ensure that the name will not overlap with a similar name in another class. No other form of underscores have meaning in the Python world. There"s no difference between class, variable, global, etc in these conventions. PHP program to generate a random number in a given range (min, max): StackOverflow Questions How do I merge two dictionaries in a single expression (taking union of dictionaries)? Question by Carl Meyer I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place. >>> x = {"a": 1, "b": 2} >>> y = {"b": 10, "c": 11} >>> z = x.update(y) >>> print(z) None >>> x {"a": 1, "b": 10, "c": 11} How can I get that final merged dictionary in z, not x? (To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I"m looking for as well.) Answer #1: How can I merge two Python dictionaries in a single expression? For dictionaries x and y, z becomes a shallowly-merged dictionary with values from y replacing those from x. In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method: z = x | y # NOTE: 3.9+ ONLY In Python 3.5 or greater: z = {**x, **y} In Python 2, (or 3.4 or lower) write a function: def merge_two_dicts(x, y): z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return z and now: z = merge_two_dicts(x, y) Explanation Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries: x = {"a": 1, "b": 2} y = {"b": 3, "c": 4} The desired result is to get a new dictionary (z) with the values merged, and the second dictionary"s values overwriting those from the first. >>> z {"a": 1, "b": 3, "c": 4} A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is z = {**x, **y} And it is indeed a single expression. Note that we can merge in with literal notation as well: z = {**x, "foo": 1, "bar": 2, **y} and now: >>> z {"a": 1, "b": 3, "foo": 1, "bar": 2, "c": 4} It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What"s New in Python 3.5 document. However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process: z = x.copy() z.update(y) # which returns None since it mutates z In both approaches, y will come second and its values will replace x"s values, thus b will point to 3 in our final result. Not yet on Python 3.5, but want a single expression If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function: def merge_two_dicts(x, y): """Given two dictionaries, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z and then you have a single expression: z = merge_two_dicts(x, y) You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number: def merge_dicts(*dict_args): """ Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key-value pairs in latter dictionaries. """ result = {} for dictionary in dict_args: result.update(dictionary) return result This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries a to g: z = merge_dicts(a, b, c, d, e, f, g) and key-value pairs in g will take precedence over dictionaries a to f, and so on. Critiques of Other Answers Don"t use what you see in the formerly accepted answer: z = dict(x.items() + y.items()) In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you"re adding two dict_items objects together, not two lists - >>> c = dict(a.items() + b.items()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: "dict_items" and "dict_items" and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items())). This is a waste of resources and computation power. Similarly, taking the union of items() in Python 3 (viewitems() in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don"t do this: >>> c = dict(a.items() | b.items()) This example demonstrates what happens when values are unhashable: >>> x = {"a": []} >>> y = {"b": []} >>> dict(x.items() | y.items()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: "list" Here"s an example where y should have precedence, but instead the value from x is retained due to the arbitrary order of sets: >>> x = {"a": 2} >>> y = {"a": 1} >>> dict(x.items() | y.items()) {"a": 2} Another hack you should not use: z = dict(x, **y) This uses the dict constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it"s difficult to read, it"s not the intended usage, and so it is not Pythonic. Here"s an example of the usage being remediated in django. Dictionaries are intended to take hashable keys (e.g. frozensets or tuples), but this method fails in Python 3 when keys are not strings. >>> c = dict(a, **b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: keyword arguments must be strings From the mailing list, Guido van Rossum, the creator of the language, wrote: I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism. and Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally, I find it more despicable than cool. It is my understanding (as well as the understanding of the creator of the language) that the intended usage for dict(**y) is for creating dictionaries for readability purposes, e.g.: dict(a=1, b=10, c=11) instead of {"a": 1, "b": 10, "c": 11} Response to comments Despite what Guido says, dict(x, **y) is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords. Again, it doesn"t work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. dict broke this consistency in Python 2: >>> foo(**{("a", "b"): None}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() keywords must be strings >>> dict(**{("a", "b"): None}) {("a", "b"): None} This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change. I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints. More comments: dict(x.items() + y.items()) is still the most readable solution for Python 2. Readability counts. My response: merge_two_dicts(x, y) actually seems much clearer to me, if we"re actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated. {**x, **y} does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging. Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first"s values being overwritten by the second"s - in a single expression. Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them: from copy import deepcopy def dict_of_dicts_merge(x, y): z = {} overlapping_keys = x.keys() & y.keys() for key in overlapping_keys: z[key] = dict_of_dicts_merge(x[key], y[key]) for key in x.keys() - overlapping_keys: z[key] = deepcopy(x[key]) for key in y.keys() - overlapping_keys: z[key] = deepcopy(y[key]) return z Usage: >>> x = {"a":{1:{}}, "b": {2:{}}} >>> y = {"b":{10:{}}, "c": {11:{}}} >>> dict_of_dicts_merge(x, y) {"b": {2: {}, 10: {}}, "a": {1: {}}, "c": {11: {}}} Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a "Dictionaries of dictionaries merge". Less Performant But Correct Ad-hocs These approaches are less performant, but they will provide correct behavior. They will be much less performant than copy and update or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dictionaries have precedence) You can also chain the dictionaries manually inside a dict comprehension: {k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7 or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced): dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2 itertools.chain will chain the iterators over the key-value pairs in the correct order: from itertools import chain z = dict(chain(x.items(), y.items())) # iteritems in Python 2 Performance Analysis I"m only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.) from timeit import repeat from itertools import chain x = dict.fromkeys("abcdefg") y = dict.fromkeys("efghijk") def merge_two_dicts(x, y): z = x.copy() z.update(y) return z min(repeat(lambda: {**x, **y})) min(repeat(lambda: merge_two_dicts(x, y))) min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()})) min(repeat(lambda: dict(chain(x.items(), y.items())))) min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))) In Python 3.8.1, NixOS: >>> min(repeat(lambda: {**x, **y})) 1.0804965235292912 >>> min(repeat(lambda: merge_two_dicts(x, y))) 1.636518670246005 >>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()})) 3.1779992282390594 >>> min(repeat(lambda: dict(chain(x.items(), y.items())))) 2.740647904574871 >>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))) 4.266070580109954 \$ uname -a Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux Resources on Dictionaries My explanation of Python"s dictionary implementation, updated for 3.6. Answer on how to add new keys to a dictionary Mapping two lists into a dictionary The official Python docs on dictionaries The Dictionary Even Mightier - talk by Brandon Rhodes at Pycon 2017 Modern Python Dictionaries, A Confluence of Great Ideas - talk by Raymond Hettinger at Pycon 2017 Answer #2: In your case, what you can do is: z = dict(list(x.items()) + list(y.items())) This will, as you want it, put the final dict in z, and make the value for key b be properly overridden by the second (y) dict"s value: >>> x = {"a":1, "b": 2} >>> y = {"b":10, "c": 11} >>> z = dict(list(x.items()) + list(y.items())) >>> z {"a": 1, "c": 11, "b": 10} If you use Python 2, you can even remove the list() calls. To create z: >>> z = dict(x.items() + y.items()) >>> z {"a": 1, "c": 11, "b": 10} If you use Python version 3.9.0a4 or greater, then you can directly use: x = {"a":1, "b": 2} y = {"b":10, "c": 11} z = x | y print(z) {"a": 1, "c": 11, "b": 10} Answer #3: An alternative: z = x.copy() z.update(y) Answer #4: Another, more concise, option: z = dict(x, **y) Note: this has become a popular answer, but it is important to point out that if y has any non-string keys, the fact that this works at all is an abuse of a CPython implementation detail, and it does not work in Python 3, or in PyPy, IronPython, or Jython. Also, Guido is not a fan. So I can"t recommend this technique for forward-compatible or cross-implementation portable code, which really means it should be avoided entirely. Answer #5: This probably won"t be a popular answer, but you almost certainly do not want to do this. If you want a copy that"s a merge, then use copy (or deepcopy, depending on what you want) and then update. The two lines of code are much more readable - more Pythonic - than the single line creation with .items() + .items(). Explicit is better than implicit. In addition, when you use .items() (pre Python 3.0), you"re creating a new list that contains the items from the dict. If your dictionaries are large, then that is quite a lot of overhead (two large lists that will be thrown away as soon as the merged dict is created). update() can work more efficiently, because it can run through the second dict item-by-item. In terms of time: >>> timeit.Timer("dict(x, **y)", "x = dict(zip(range(1000), range(1000))) y=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000) 15.52571702003479 >>> timeit.Timer("temp = x.copy() temp.update(y)", "x = dict(zip(range(1000), range(1000))) y=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000) 15.694622993469238 >>> timeit.Timer("dict(x.items() + y.items())", "x = dict(zip(range(1000), range(1000))) y=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000) 41.484580039978027 IMO the tiny slowdown between the first two is worth it for the readability. In addition, keyword arguments for dictionary creation was only added in Python 2.3, whereas copy() and update() will work in older versions. PHP program to generate a random number in a given range (min, max): StackOverflow Questions How to execute a program or call a system command? Question by alan lai How do you call an external command (as if I"d typed it at the Unix shell or Windows command prompt) from within a Python script? Answer #1: Use the subprocess module in the standard library: import subprocess subprocess.run(["ls", "-l"]) The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...). Even the documentation for os.system recommends using subprocess instead: The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes. On Python 3.4 and earlier, use subprocess.call instead of .run: subprocess.call(["ls", "-l"]) Answer #2: Here"s a summary of the ways to call external programs and the advantages and disadvantages of each: os.system("some_command with args") passes the command and arguments to your system"s shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example: os.system("some_command < input_file | another_command > output_file") However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, et cetera. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs. See the documentation. stream = os.popen("some_command with args") will do the same thing as os.system except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don"t need to worry about escaping anything. See the documentation. The Popen class of the subprocess module. This is intended as a replacement for os.popen, but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you"d say: print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read() instead of print os.popen("echo Hello World").read() but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See the documentation. The call function from the subprocess module. This is basically just like the Popen class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example: return_code = subprocess.call("echo Hello World", shell=True) See the documentation. If you"re on Python 3.5 or later, you can use the new subprocess.run function, which is a lot like the above but even more flexible and returns a CompletedProcess object when the command finishes executing. The os module also has all of the fork/exec/spawn functions that you"d have in a C program, but I don"t recommend using them directly. The subprocess module should probably be what you use. Finally, please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. There are serious security implications if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code: print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read() and imagine that the user enters something "my mama didnt love me && rm -rf /" which could erase the whole filesystem. Answer #3: Typical implementation: import subprocess p = subprocess.Popen("ls", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, retval = p.wait() You are free to do what you want with the stdout data in the pipe. In fact, you can simply omit those parameters (stdout= and stderr=) and it"ll behave like os.system(). Answer #4: Some hints on detaching the child process from the calling one (starting the child process in background). Suppose you want to start a long task from a CGI script. That is, the child process should live longer than the CGI script execution process. The classical example from the subprocess module documentation is: import subprocess import sys # Some code here pid = subprocess.Popen([sys.executable, "longtask.py"]) # Call subprocess # Some more code here The idea here is that you do not want to wait in the line "call subprocess" until the longtask.py is finished. But it is not clear what happens after the line "some more code here" from the example. My target platform was FreeBSD, but the development was on Windows, so I faced the problem on Windows first. On Windows (Windows XP), the parent process will not finish until the longtask.py has finished its work. It is not what you want in a CGI script. The problem is not specific to Python; in the PHP community the problems are the same. The solution is to pass DETACHED_PROCESS Process Creation Flag to the underlying CreateProcess function in Windows API. If you happen to have installed pywin32, you can import the flag from the win32process module, otherwise you should define it yourself: DETACHED_PROCESS = 0x00000008 pid = subprocess.Popen([sys.executable, "longtask.py"], creationflags=DETACHED_PROCESS).pid /* UPD 2015.10.27 @eryksun in a comment below notes, that the semantically correct flag is CREATE_NEW_CONSOLE (0x00000010) */ On FreeBSD we have another problem: when the parent process is finished, it finishes the child processes as well. And that is not what you want in a CGI script either. Some experiments showed that the problem seemed to be in sharing sys.stdout. And the working solution was the following: pid = subprocess.Popen([sys.executable, "longtask.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) I have not checked the code on other platforms and do not know the reasons of the behaviour on FreeBSD. If anyone knows, please share your ideas. Googling on starting background processes in Python does not shed any light yet. Answer #5: import os os.system("your command") Note that this is dangerous, since the command isn"t cleaned. I leave it up to you to google for the relevant documentation on the "os" and "sys" modules. There are a bunch of functions (exec* and spawn*) that will do similar things. ```
``` ```
``` (adsbygoogle = window.adsbygoogle || []).push({}); Shop Best laptop for Sims 4\$ Best laptop for Zoom\$499 Best laptop for Minecraft\$590 Best laptop for engineering student\$ Best laptop for development\$ Best laptop for Cricut Maker\$ Best laptop for hacking\$890 Best laptop for Machine Learning\$950 Latest questions NUMPYNUMPY psycopg2: insert multiple rows with one query 12 answers NUMPYNUMPY How to convert Nonetype to int or string? 12 answers NUMPYNUMPY How to specify multiple return types using type-hints 12 answers NUMPYNUMPY Javascript Error: IPython is not defined in JupyterLab 12 answers All questions ```
``` ```
``` ```
``` News 26/05/2022 Twitter Founder Jack Dorsey Officially Steps Down as CEO 26/05/2022 Zotac Unveils Gaming Backpack with Intel Tiger Lake and NVIDIA RTX A4500 26/05/2022 Chrome 102 released Wiki __del__ Python OpenCV | cv2.putText () method __del__ numpy.arctan2 () in Python __del__ Python | os.path.realpath () method around Python OpenCV | cv2.circle () method cvtcolor Python OpenCV cv2.cvtColor () method Python Methods and Functions Python - Move item to the end of the list Counters time.perf_counter () function in Python __dict__ Check if one list is a subset of another in Python __del__ Python os.path.join () method © 2017—2022 Python Engineering Hub EN | ES | DE | FR | IT | RU | TR | PL | PT | JP | KR | CN | HI | NL Python.Engineering is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com Python Loops Counters NumPy NLP Regular Expressions Wiki Tech news Python Wiki StackOverflow PHP JavaScript Books All books Computations Development Cryptography For dummies Big Data document.addEventListener("DOMContentLoaded", () => { let arrayCode = document.querySelectorAll('pre'); arrayCode.forEach(element => { element.classList.add("prettyprint"); }); }); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-Q022WLXW4X'); ```